Creating play/pause functions with current audio javascript

半世苍凉 提交于 2020-01-17 08:15:18

问题


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);

回答1:


var audios= Array.prototype.map.call(document.getElementsByClassName("myButton"),function(el){
    var audio=new Audio();
    audio.preload="none";//=> not preloaded
    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.pause());
});

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



来源:https://stackoverflow.com/questions/44083628/creating-play-pause-functions-with-current-audio-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!