0

When play is pressed the file .mp3 should play when clicked again the .mp3 should stop and reset audio.

If another play button is pressed while a sound is already playing it should stop the audio , reset its time to 0, and play the new audio.

The goal is to play only one sound at a time so sounds do not overlap while fetching the file name from 'key' and add the directory + .mp3 in javascript / jquery after.

The main purpose behind this approach is to prevent a user to right click save target as and obscure the mp3 location.

For some reason It is not working.

<span class="play" key="cef83b993c716dd543b6fa4f053cc4a4">Play</span> 
<br>
<span class="play" key="7a5c5d3940f65d81489a0c18f877114b">Play</span>

<script>
var currentAudio = null;
$(".play").click(function () {
    if(currentAudio != null && !currentAudio.paused && currentAudio != this){
      currentAudio.pause();
      currentAudio.currentTime = 0;
      $( this ).removeClass( "pause" );
      $( this ).addClass( "play" ); // switch to play button
    }
    var audio = ("beats/" + $(this).attr('key') + ".mp3");
    if (audio.paused) {
        audio.play();
        currentAudio = audio;
        $( this ).addClass( "pause" ); // switch to pause button
    } else {
        audio.pause();
      $( this ).removeClass( "pause" );
      $( this ).addClass( "play" ); // switch to play button
    }
});
</script>
Jeff
  • 1,018
  • 1
  • 15
  • 33

1 Answers1

1

I imagine something like this:

 $(".play").on('click',function(){
     var key = $(this).attr('key');     
     EvalSound(key);
 });

var thissound = new Audio();


var currentKey;
function EvalSound(key) {



 if(currentKey !== key)
   thissound.src = "http://designlab360.org/fhi/splash/dev2/audio/" + key + ".mp3";      
   currentKey = key; 

 if (thissound.paused)
            thissound.play();
    else
        thissound.pause();
        thissound.currentTime = 0;
         currentPlayer = thissound;
}

See http://jsfiddle.net/sjmcpherso/pt3cx1eo/11/

sjm
  • 5,378
  • 1
  • 26
  • 37
  • Hey Sjm, that is very close, the only thing is it doesn't stop if you press button again, it resets from beggining – Jeff Sep 21 '15 at 03:12
  • I think it needs a ! statement somewhere, this is where I am at http://jsfiddle.net/pt3cx1eo/8/ based off http://stackoverflow.com/questions/30030123/stopping-pausing-audio-when-another-audio-file-is-clicking-using-jquery?rq=1 – Jeff Sep 21 '15 at 03:29
  • This is perfect, Exactaly what I was trying to do! Thanks SJM! – Jeff Sep 21 '15 at 04:12
  • You should reformat your code, to make it clear that on each call `thissound.currentTime` is set to 0, like it is right now, one could think that it will only occur in the `else` statement. – Kaiido Sep 21 '15 at 05:28