Collin Willson Collin Willson -4 years ago 130
HTML Question

Creating play/pause functions with current audio javascript

I have an extension for chrome I am working on, I have an HTML popup that has buttons that play audio. I don't think my approach is the most elegant and I am having trouble exploring ways to shrink this down. I know this is very inefficient. I want to be able to tell which button was clicked on the HTML page, then using that ID play the audio file with that same ID. The way I have it now is using the EventListener in javascript to use multiple functions to stop or play. Is there a way to put all of this in one function through javascript or jquery to fix this chaos? Since I am doing this on a chrome extension I cannot use Javascript in the HTML document.

Currently I have my HTML like this;

<script type="text/javascript" src="js/audio.js"></script>

<a href="#" class="myButton" id="stopbutton">Stop Audio</a>
<a href="#" class="myButton" id="aud1">Audio 1</a>
<a href="#" class="myButton" id="aud2">Audio 2</a>
<a href="#" class="myButton" id="aud3">Audio 3</a>


My JS file like this to create the variables for my audio files.

var aud1 = new Audio();
var aud2 = new Audio();
var aud3 = new Audio();


Along with this function to start playback when a button is selected with the coresponding name.

function aud1play() {
aud1.src = "mp3/aud1.mp3";
aud1.play();
}
document.getElementById('aud1').addEventListener('click', aud1play);

//you get the trend


To stop my audio I have the following function:

function audstop() {
aud1.pause;
aud2.pause;
aud3.pause;
document.getElementById('stopbutton').addEventListener('click', audstop);

Answer Source
var audios= Array.prototype.map.call(document.getElementsByClassName("myButton"),function(el){
    var audio=new Audio();
    audio.src="mp3/"+el.id+".mp3";
    el.onclick=audio.play.bind(audio);
    return audio;
});

Simply iterate over your buttons, create an audio element with the right src for it, and bind the onclick listener to its play function. Then map the audio elements.

document.getElementById('stopbutton').addEventListener('click', function(){
    audios.forEach(audio=>audio.stop());
});

To stop, simply iterate over the audio elements and call the stop function on each...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download