Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

JavaScript JS audio player not working on Tumblr blog

xcoder

Coder
Hey all, first time here. Just would like to get some help in knowing why my audio player is not working on my blog. It is showing 0:00 for the duration time. I have the code here to look through. If you need my blog's link, please let me know. Thanks.


JavaScript:
    import lottieWeb from 'https://cdn.skypack.dev/lottie-web';
    class AudioPlayer extends HTMLElement {
      constructor() {
        super();
        const template = document.querySelector('template');
        const templateContent = template.content;
        const shadow = this.attachShadow({
          mode: 'open'
        });
        shadow.appendChild(templateContent.cloneNode(true));
      }
      connectedCallback() {
        everything(this);
      }
    }
    const everything = function(element) { 
  const shadow = element.shadowRoot;

    const audioPlayerContainer = shadow.getElementById('audio-player-container');
    const playIconContainer = shadow.getElementById('play-icon');
    const seekSlider = shadow.getElementById('seek-slider');
    const volumeSlider = shadow.getElementById('volume-slider');
    const muteIconContainer = shadow.getElementById('mute-icon');
    const audio = shadow.querySelector('audio');
    const durationContainer = shadow.getElementById('duration');
    const currentTimeContainer = shadow.getElementById('current-time');
    const outputContainer = shadow.getElementById('volume-output');
    let playState = 'play';
    let muteState = 'unmute';
    let raf = null;
      audio.src = element.getAttribute('data-src');
      const playAnimation = lottieWeb.loadAnimation({
        container: playIconContainer,
        path: 'https://maxst.icons8.com/vue-static/landings/animated-icons/icons/pause/pause.json',
        renderer: 'svg',
        loop: false,
        autoplay: false,
        name: "Play Animation",
      });
      const muteAnimation = lottieWeb.loadAnimation({
        container: muteIconContainer,
        path: 'https://maxst.icons8.com/vue-static/landings/animated-icons/icons/mute/mute.json',
        renderer: 'svg',
        loop: false,
        autoplay: false,
        name: "Mute Animation",
      });
      playAnimation.goToAndStop(14, true);
      const whilePlaying = () => {
        seekSlider.value = Math.floor(audio.currentTime);
        currentTimeContainer.textContent = calculateTime(seekSlider.value);
        audioPlayerContainer.style.setProperty('--seek-before-width', `${seekSlider.value / seekSlider.max * 100}%`);
        raf = requestAnimationFrame(whilePlaying);
      }
      const showRangeProgress = (rangeInput) => {
        if (rangeInput === seekSlider) audioPlayerContainer.style.setProperty('--seek-before-width', rangeInput.value / rangeInput.max * 100 + '%');
        else audioPlayerContainer.style.setProperty('--volume-before-width', rangeInput.value / rangeInput.max * 100 + '%');
      }
      const calculateTime = (secs) => {
       const minutes = Math.floor(secs / 60);
       const seconds = Math.floor(secs % 60);
       const returnedSeconds = seconds < 10 ? `0${seconds}`:`${seconds}`;
       return `${minutes}:${returnedSeconds}`;
     }
      const displayDuration = () => {
        durationContainer.textContent = calculateTime(audio.duration);
      }
      const setSliderMax = () => {
        seekSlider.max = Math.floor(audio.duration);
      }
      const displayBufferedAmount = () => {
        const bufferedAmount = Math.floor(audio.buffered.end(audio.buffered.length - 1));
        audioPlayerContainer.style.setProperty('--buffered-width', `${(bufferedAmount / seekSlider.max) * 100}%`);
      }
      if (audio.readyState > 0) {
        displayDuration();
        setSliderMax();
        displayBufferedAmount();
      } else {
        audio.addEventListener('loadedmetadata', () => {
          displayDuration();
          setSliderMax();
          displayBufferedAmount();
        });
      }
      playIconContainer.addEventListener('click', () => {
        if (playState === 'play') {
          audio.play();
          playAnimation.playSegments([14, 27], true);
          requestAnimationFrame(whilePlaying);
          playState = 'pause';
        } else {
          audio.pause();
          playAnimation.playSegments([0, 14], true);
          cancelAnimationFrame(raf);
          playState = 'play';
        }
      });
      muteIconContainer.addEventListener('click', () => {
        if (muteState === 'unmute') {
          muteAnimation.playSegments([0, 15], true);
          audio.muted = true;
          muteState = 'mute';
        } else {
          muteAnimation.playSegments([15, 25], true);
          audio.muted = false;
          muteState = 'unmute';
        }
      });
      
      audio.addEventListener("ended", () => {
  playIconContainer.click();
  cancelAnimationFrame(raf);
  currentTimeContainer.textContent = "0.00";
  seekSlider.value = "0";
});
      
      audio.addEventListener('progress', displayBufferedAmount);
      seekSlider.addEventListener('input', (e) => {
        showRangeProgress(e.target);
        currentTimeContainer.textContent = calculateTime(seekSlider.value);
        if (!audio.paused) {
          cancelAnimationFrame(raf);
        }
      });
      seekSlider.addEventListener('change', () => {
        audio.currentTime = seekSlider.value;
        if (!audio.paused) {
          requestAnimationFrame(whilePlaying);
        }
      });
      volumeSlider.addEventListener('input', (e) => {
        const value = e.target.value;
        showRangeProgress(e.target);
        outputContainer.textContent = value;
        audio.volume = value / 100;
      });
      if ('mediaSession' in navigator) {
        navigator.mediaSession.metadata = new MediaMetadata({
          title: 'Evenstar',
          artist: 'Howard Shore',
          album: 'The Lord of the Rings'
        });
        navigator.mediaSession.setActionHandler('play', () => {
          if (playState === 'play') {
            audio.play();
            playAnimation.playSegments([14, 27], true);
            requestAnimationFrame(whilePlaying);
            playState = 'pause';
          } else {
            audio.pause();
            playAnimation.playSegments([0, 14], true);
            cancelAnimationFrame(raf);
            playState = 'play';
          }
        });
        navigator.mediaSession.setActionHandler('pause', () => {
          if (playState === 'play') {
            audio.play();
            playAnimation.playSegments([14, 27], true);
            requestAnimationFrame(whilePlaying);
            playState = 'pause';
          } else {
            audio.pause();
            playAnimation.playSegments([0, 14], true);
            cancelAnimationFrame(raf);
            playState = 'play';
          }
        });
        navigator.mediaSession.setActionHandler('seekbackward', (details) => {
          audio.currentTime = audio.currentTime - (details.seekOffset || 10);
        });
        navigator.mediaSession.setActionHandler('seekforward', (details) => {
          audio.currentTime = audio.currentTime + (details.seekOffset || 10);
        });
        navigator.mediaSession.setActionHandler('seekto', (details) => {
          if (details.fastSeek && 'fastSeek' in audio) {
            audio.fastSeek(details.seekTime);
            return;
          }
          audio.currentTime = details.seekTime;
        });
        navigator.mediaSession.setActionHandler('stop', () => {
          audio.currentTime = 0;
          seekSlider.value = 0;
          audioPlayerContainer.style.setProperty('--seek-before-width', '0%');
          currentTimeContainer.textContent = '0:00';
          if (playState === 'pause') {
            playAnimation.playSegments([0, 14], true);
            cancelAnimationFrame(raf);
            playState = 'play';
          }
        });
      }
    }
    customElements.define('audio-player', AudioPlayer)
 
Hey all, first time here. Just would like to get some help in knowing why my audio player is not working on my blog. It is showing 0:00 for the duration time. I have the code here to look through. If you need my blog's link, please let me know. Thanks.


JavaScript:
    import lottieWeb from 'https://cdn.skypack.dev/lottie-web';
    class AudioPlayer extends HTMLElement {
      constructor() {
        super();
        const template = document.querySelector('template');
        const templateContent = template.content;
        const shadow = this.attachShadow({
          mode: 'open'
        });
        shadow.appendChild(templateContent.cloneNode(true));
      }
      connectedCallback() {
        everything(this);
      }
    }
    const everything = function(element) {
  const shadow = element.shadowRoot;

    const audioPlayerContainer = shadow.getElementById('audio-player-container');
    const playIconContainer = shadow.getElementById('play-icon');
    const seekSlider = shadow.getElementById('seek-slider');
    const volumeSlider = shadow.getElementById('volume-slider');
    const muteIconContainer = shadow.getElementById('mute-icon');
    const audio = shadow.querySelector('audio');
    const durationContainer = shadow.getElementById('duration');
    const currentTimeContainer = shadow.getElementById('current-time');
    const outputContainer = shadow.getElementById('volume-output');
    let playState = 'play';
    let muteState = 'unmute';
    let raf = null;
      audio.src = element.getAttribute('data-src');
      const playAnimation = lottieWeb.loadAnimation({
        container: playIconContainer,
        path: 'https://maxst.icons8.com/vue-static/landings/animated-icons/icons/pause/pause.json',
        renderer: 'svg',
        loop: false,
        autoplay: false,
        name: "Play Animation",
      });
      const muteAnimation = lottieWeb.loadAnimation({
        container: muteIconContainer,
        path: 'https://maxst.icons8.com/vue-static/landings/animated-icons/icons/mute/mute.json',
        renderer: 'svg',
        loop: false,
        autoplay: false,
        name: "Mute Animation",
      });
      playAnimation.goToAndStop(14, true);
      const whilePlaying = () => {
        seekSlider.value = Math.floor(audio.currentTime);
        currentTimeContainer.textContent = calculateTime(seekSlider.value);
        audioPlayerContainer.style.setProperty('--seek-before-width', `${seekSlider.value / seekSlider.max * 100}%`);
        raf = requestAnimationFrame(whilePlaying);
      }
      const showRangeProgress = (rangeInput) => {
        if (rangeInput === seekSlider) audioPlayerContainer.style.setProperty('--seek-before-width', rangeInput.value / rangeInput.max * 100 + '%');
        else audioPlayerContainer.style.setProperty('--volume-before-width', rangeInput.value / rangeInput.max * 100 + '%');
      }
      const calculateTime = (secs) => {
       const minutes = Math.floor(secs / 60);
       const seconds = Math.floor(secs % 60);
       const returnedSeconds = seconds < 10 ? `0${seconds}`:`${seconds}`;
       return `${minutes}:${returnedSeconds}`;
     }
      const displayDuration = () => {
        durationContainer.textContent = calculateTime(audio.duration);
      }
      const setSliderMax = () => {
        seekSlider.max = Math.floor(audio.duration);
      }
      const displayBufferedAmount = () => {
        const bufferedAmount = Math.floor(audio.buffered.end(audio.buffered.length - 1));
        audioPlayerContainer.style.setProperty('--buffered-width', `${(bufferedAmount / seekSlider.max) * 100}%`);
      }
      if (audio.readyState > 0) {
        displayDuration();
        setSliderMax();
        displayBufferedAmount();
      } else {
        audio.addEventListener('loadedmetadata', () => {
          displayDuration();
          setSliderMax();
          displayBufferedAmount();
        });
      }
      playIconContainer.addEventListener('click', () => {
        if (playState === 'play') {
          audio.play();
          playAnimation.playSegments([14, 27], true);
          requestAnimationFrame(whilePlaying);
          playState = 'pause';
        } else {
          audio.pause();
          playAnimation.playSegments([0, 14], true);
          cancelAnimationFrame(raf);
          playState = 'play';
        }
      });
      muteIconContainer.addEventListener('click', () => {
        if (muteState === 'unmute') {
          muteAnimation.playSegments([0, 15], true);
          audio.muted = true;
          muteState = 'mute';
        } else {
          muteAnimation.playSegments([15, 25], true);
          audio.muted = false;
          muteState = 'unmute';
        }
      });
    
      audio.addEventListener("ended", () => {
  playIconContainer.click();
  cancelAnimationFrame(raf);
  currentTimeContainer.textContent = "0.00";
  seekSlider.value = "0";
});
    
      audio.addEventListener('progress', displayBufferedAmount);
      seekSlider.addEventListener('input', (e) => {
        showRangeProgress(e.target);
        currentTimeContainer.textContent = calculateTime(seekSlider.value);
        if (!audio.paused) {
          cancelAnimationFrame(raf);
        }
      });
      seekSlider.addEventListener('change', () => {
        audio.currentTime = seekSlider.value;
        if (!audio.paused) {
          requestAnimationFrame(whilePlaying);
        }
      });
      volumeSlider.addEventListener('input', (e) => {
        const value = e.target.value;
        showRangeProgress(e.target);
        outputContainer.textContent = value;
        audio.volume = value / 100;
      });
      if ('mediaSession' in navigator) {
        navigator.mediaSession.metadata = new MediaMetadata({
          title: 'Evenstar',
          artist: 'Howard Shore',
          album: 'The Lord of the Rings'
        });
        navigator.mediaSession.setActionHandler('play', () => {
          if (playState === 'play') {
            audio.play();
            playAnimation.playSegments([14, 27], true);
            requestAnimationFrame(whilePlaying);
            playState = 'pause';
          } else {
            audio.pause();
            playAnimation.playSegments([0, 14], true);
            cancelAnimationFrame(raf);
            playState = 'play';
          }
        });
        navigator.mediaSession.setActionHandler('pause', () => {
          if (playState === 'play') {
            audio.play();
            playAnimation.playSegments([14, 27], true);
            requestAnimationFrame(whilePlaying);
            playState = 'pause';
          } else {
            audio.pause();
            playAnimation.playSegments([0, 14], true);
            cancelAnimationFrame(raf);
            playState = 'play';
          }
        });
        navigator.mediaSession.setActionHandler('seekbackward', (details) => {
          audio.currentTime = audio.currentTime - (details.seekOffset || 10);
        });
        navigator.mediaSession.setActionHandler('seekforward', (details) => {
          audio.currentTime = audio.currentTime + (details.seekOffset || 10);
        });
        navigator.mediaSession.setActionHandler('seekto', (details) => {
          if (details.fastSeek && 'fastSeek' in audio) {
            audio.fastSeek(details.seekTime);
            return;
          }
          audio.currentTime = details.seekTime;
        });
        navigator.mediaSession.setActionHandler('stop', () => {
          audio.currentTime = 0;
          seekSlider.value = 0;
          audioPlayerContainer.style.setProperty('--seek-before-width', '0%');
          currentTimeContainer.textContent = '0:00';
          if (playState === 'pause') {
            playAnimation.playSegments([0, 14], true);
            cancelAnimationFrame(raf);
            playState = 'play';
          }
        });
      }
    }
    customElements.define('audio-player', AudioPlayer)
Hi there,
So before we proceed on a more technical level, let's establish a few things. So there may not be anything wrong with your code, but more to do with a policy that started off being Google's idea for Chrome, but since it was "a verrryyyyyy GREAT IDEA" (note the sarcasm lol) that it just had to be implemented on all browsers. This of course is the Autoplay policy, which was implemented back in 2018. To quote myself from another thread where I am helping out another user going through the same issues:
So according to Google's own documentation, this change in the autoplay policy is intended to not only give users a better user experience, but reduce data usage/consumption so that it doesn't become a bottleneck for a network, discourage users from installing ad blockers. This was supposedly only going to be just on Google Chrome, but other browser vendors decided that it was a "great idea" (note my overly exaggerated sarcastic tone with that one lol) so they have also implemented these changes as well. So now by default, browsers will disable autoplay, and the only way to get to autoplay to work is to do one or more of the following:


As per Google's docs
  • Muted autoplay is always allowed.
  • Autoplay with sound is allowed if:
  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound
 
Hi there,
So before we proceed on a more technical level, let's establish a few things. So there may not be anything wrong with your code, but more to do with a policy that started off being Google's idea for Chrome, but since it was "a verrryyyyyy GREAT IDEA" (note the sarcasm lol) that it just had to be implemented on all browsers. This of course is the Autoplay policy, which was implemented back in 2018. To quote myself from another thread where I am helping out another user going through the same issues:
So what should I do if I want to click the play button every time? And what to do about the duration 0:00? It should still show the duration time even when not playing anything. I don't understand.

PS - I don't use Chrome, I have Firefox, and I have the latest version.
 
So what should I do if I want to click the play button every time? And what to do about the duration 0:00? It should still show the duration time even when not playing anything. I don't understand.

PS - I don't use Chrome, I have Firefox, and I have the latest version.
As I mentioned in my earlier statement...
Code:
a policy that started off being Google's idea for Chrome, but since it was "a verrryyyyyy GREAT IDEA" (note the sarcasm lol) that it just had to be implemented on all browsers

In other words, really doesn't matter what browser you are using, this has been implemented across the board: Edge, Firefox, Chrome, Safari, etc. To answer your question, unfortunately yes, you are going to have to implement some functionality to force the user to interact with the page before any sound can be autoplayed...yes, I know annoying to all hell and back, but tis the way the web overlords have chosen, in the name of "user experience". There is another way to allow autoplay, but that involves your users to manually change their settings in order to be able to allow autoplay
 
Last edited:
Hi @xcoder,

If your Audio player code is not working on Tumblr blog, you can directly upload audio file there in your blog. I have tried it and seems working fine at my end.

Thanks
Hi Kane. You mean through the Theme Assets, right? I have the audio player JS code uploaded through that. Unless this is different? Please tell me more.
 
Hi Kane. You mean through the Theme Assets, right? I have the audio player JS code uploaded through that. Unless this is different? Please tell me more.
As you mentioned you have audio player JS code so you are trying to put audio in blog using JS code right? My perspective is , if you have audio file in MP3 format, you can directly upload it in the blog.

Thanks
 
As you mentioned you have audio player JS code so you are trying to put audio in blog using JS code right? My perspective is , if you have audio file in MP3 format, you can directly upload it in the blog.

Thanks
Oh ok, no it's m4a. How do you directly upload it in there? Anything else I can do?
 
I have been working on it, but am still not able to get it to work. Could someone please look into it and maybe try fixing it up? I am just tired of trying. I have been trying to fix it last few days now.
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom