Audio tag - Fade and individual playback

1

I have a page with multiple audios, using the native html5 player. I 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>
    
asked by anonymous 26.12.2017 / 19:57

1 answer

0

I know it's an old question, but I'll leave an example interaction playing with the 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><audioid="player" controls></audio>
  

This example was just a beta, in a second moment I will edit the code to make it leaner and parameterizable. But it can be a starting point to achieve what you are looking for if your goal is to have multiple players and when selecting a new one fadeout what you are playing and then start the new one, leave a comment that I edit the answer. / p>

    
21.01.2018 / 17:20