Tag <audio> - Fade and individual playback

Asked

Viewed 48 times

1

I have a page with several audios, using the native player Html5. Need to add fade in/out to the audios and somehow allow only one audio to play at a time. Any light? rs

<audio class="borda-player" src="audios/9.mp3" controls></audio>

  • You are using jQuery in your project?

  • Check out this article https://dailygit.com/fade-in-and-fade-audio-with-html5-api/

  • Does fade refer to diminishing sound? I believe this is a start https://answall.com/a/168525/3635

  • @Thallesoliveira Managed to solve?

1 answer

0

I know it’s an old question, but I’ll leave an example of interaction playing with volume control.

$('document').ready(function() {
  var player = document.getElementById("player");
  var auxVolume = document.getElementById("player").volume;
  var lastVolume = 0;
  var currentTrack = -1;
  var onFade = false;
  var playlist = [
      {
      titulo: 'Onda',
      url: 'http://www.sample-videos.com/audio/mp3/wave.mp3',
      duracao: '00:00:45'
    },
    {
      titulo: 'Aplausos',
      url: 'http://www.sample-videos.com/audio/mp3/crowd-cheering.mp3',
      duracao: '00:00:27'
    }

  ];

  var fadeOnStart = function() {
    if (player.currentTime == 0) {
      var originalVolume = auxVolume;
      player.volume = 0;
      $(player).animate({
        volume: auxVolume
      }, 2000);
    }
  };

  var fadeOut = function() {
    if (!onFade) {
      var originalVolume = auxVolume;
      onFade = true;
      $(player).animate({
        volume: 0
      }, 2000, function() {
        onFade = false;
        lastVolume = originalVolume;
        playNext();
        

      });
    }
  }

  var playNext = function() {
    if((currentTrack < playlist.length -1)){
      currentTrack++
    }else{
      currentTrack = 0;
    }
    
      player.setAttribute('src', playlist[currentTrack].url);
      player.load();
      player.volume = lastVolume;
      player.play();
  }

  var monitor = function() {
    if (player.currentTime >= (player.duration - 2)) {
      fadeOut();
    }
  }

  var start = function() {
    lastVolume = 0.35;
    playNext();
    
    player.onplay = function() {
      fadeOnStart()
    };
    player.ontimeupdate = function() {
      monitor()
    }
    player.onvolumechange = function() {
      auxVolume = player.volume;
    }
  }();
});
audio {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<audio id="player" controls></audio>

This example was just a beta, in a second moment I will edit the code to make it more streamlined and parameterizable. But it can be a starting point to achieve what you’re looking for, if your goal is to have multiple players and when selecting a new one fade out what you’re playing and then start the new one, leave a comment and I’ll edit the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.