Kuwame Brown
Kuwame Brown

Reputation: 533

play music javascript

My code is below. Basically, my goal is once the user clicks certain button, I would get this button's id and send it through ajax, then return the mp3 url based on the id specified and play the sound. Everything is working perfectly fine, but the problem is I do not know how to stop or pause the music. I've tried audio.stop(), or audio.pause(). Neither one is working.

Once the user clicks certain button, i would like to stop all the music and play the new one that is clicked.

$('.play_sound').click(function(event){
event.preventDefault();
var data_id = $(this).parents('tr').attr('data-id');

  $.post('ajax/play_sound.php', {data_id: data_id}, function(data){
     var audio = new Audio(data);
     audio.play();
  });

});

Upvotes: 1

Views: 189

Answers (2)

carlodurso
carlodurso

Reputation: 2894

you should create a audio tag

<audio src="audio.mp3" id="audio"></audio>

then

document.getElementById('audio').pause();

$.post('ajax/play_sound.php', {data_id: data_id}, function(data){
    document.getElementById('audio').src = data;
    document.getElementById('audio').play();
});

Haven't tested, hope it woks.

Upvotes: 0

pce
pce

Reputation: 5931

Because you created audio as a local variable in the scope of the anonymous function, you can't pause it.

The simplest solution is to make audio global.

if you plan to support more than one audio object, a better approach is to create an Object like an AudioPool and you could also add Events like "ended".

var audio;

$('.pause_sound').click(function(event){
  event.preventDefault();
  if (!audio.paused) {
    audio.pause();
  }
});


$('.stop_sound').click(function(event){
  event.preventDefault();
  audio.stop();
});

$('.play_sound').click(function(event){
event.preventDefault();
var data_id = $(this).parents('tr').attr('data-id');

  $.post('ajax/play_sound.php', {data_id: data_id}, function(data){
     // audio of global scope
     audio = new Audio(data);
     audio.play();
  });

});

An alternative solution is suggested by carlodurso to query the DOM and create an HTML element for audio.

Upvotes: 1

Related Questions