Reputation: 125
I'm making a chat application and one of the features is sending a sound. The HTML that gets sent is the following:
<p>
<audio autoplay>
<source src="sounds/lol.mp3" type="audio/mpeg">
</audio>
LOL
<a href="#" id="soundStop">Stop</a>
<a href="#" id="soundPlay" style="display:none;">Play</a>
</p>
The 'autoplay' works fine when it is sent the first time. So now i need a play/stop link to hear the sound again as many times as you want. I have the following Javascript:
$(document).on('click', '#soundStop', function(e) {
$(this).hide();
$(this).next("a").show();
$('audio').each(function(){
this.pause();
this.currentTime = 0;
});
e.preventDefault();
});
$(document).on('click', '#soundPlay', function(e) {
$(this).hide();
$(this).prev("a").show();
$(this).closest("audio").play();
//alert("play sound again!");
e.preventDefault();
});
The stop function works (although I'm not sure targeting all 'audio' elements is a good idea). But I'm stuck at how to target the audio element to .play() in the second function. I might be going at this the completely wrong way?
Any help or advice is appreciated.
EDIT: Just to clarify, there might be multiple instances of these sounds that get sent which is why I need a way to only target that specific 'audio' for each.
Upvotes: 2
Views: 12739
Reputation: 1337
Why dont you use the Ready to Use Controls of audio tag. It'll serve your purpose.
Try this code :
<!DOCTYPE html>
<html>
<body>
<audio autoplay controls>
<source src="horse.ogg" type="audio/ogg">
</audio>
</body>
</html>
Customer Controls
<!DOCTYPE html>
<html>
<body>
<audio id="player" src="horse.ogg"></audio>
<div>
<button onclick="document.getElementById('player').play()">Play</button>
<button onclick="document.getElementById('player').pause()">Pause</button>
<button onclick="document.getElementById('player').volume+=0.1">Volume Up</button>
<button onclick="document.getElementById('player').volume-=0.1">Volume Down</button>
</div>
</body>
</html>
Upvotes: 4