Stopping/pausing 单击按钮时的音频

Stopping/pausing audio when button is clicked

我希望能够通过单击一个按钮来播放和暂停 mp3 文件,我目前播放的是音频,但如果我再次单击它,它不会停止。

根据我在其他帖子上看到的,执行此操作的方法是 audio.pause(),但它对我的代码没有影响。

代码:

function playStop(){
                document.getElementById('playControl').style.visibility='visible';
                var audio = new Audio('mp3/audio.mp3');
                
                if (document.getElementById('playbtn').innerHTML=="❚❚"){
                    audio.pause();
                    audio.currentTime = 0;
                    document.getElementById('playbtn').innerHTML="▷";
                }
                else if(document.getElementById('playbtn').innerHTML=="▷"){
                    audio.play();                
                    document.getElementById('playbtn').innerHTML="❚❚";
                }
            }  

注意:更改 html 内容的行有效,只有 audio.pause() 方法无效。

蒂亚

根据文档,audio.pause() 应该按照您的使用方式工作。您的问题是每次 playStop() 您都在创建一个新的 Audio 元素 被调用。

在第一次调用时,创建并播放音频元素(目前有效)。但是第二次创建了音频元素的新实例,并根据您的条件直接暂停,而第一个实例将愉快地继续播放。

固定码

// have a reference on top level to the "audio" var so it will be 
// correctly played and paused. 
var audio

function playStop() {

    // check wether the audio was already created and do so if not.
    // also create the playcontrol once.
    if (!audio) {
        audio = new Audio('mp3/audio.mp3');
        document.getElementById('playControl').style.visibility = 'visible';
    }

    if (document.getElementById('playbtn').innerHTML == "❚❚") {
        audio.pause();
        // since you only play and pause I do not see the sense behind setting the 
        // currentTime to 0. I will comment it out therefore.
        // audio.currentTime = 0;
        document.getElementById('playbtn').innerHTML = "▷";
    } else if (document.getElementById('playbtn').innerHTML == "▷") {
        audio.play();
        document.getElementById('playbtn').innerHTML = "❚❚";
    }
}

增强代码

为了使代码更稳定,我建议增强您的 if 条件。 audio 对象本身会保存曲目,无论是否正在播放,可通过 audio.paused

访问
// have a reference on top level to the "audio" var so it will be 
// correctly played and paused. 
var audio

function playStop() {

    // check wether the audio was already created and do so if not.
    // also show the playcontrol on creation.
    if (!audio) {
        audio = new Audio('mp3/audio.mp3');
        document.getElementById('playControl').style.visibility = 'visible';
    }

    // use audio.paused prop for being more consistent. The content of the play button 
    // could be changed without breaking the code now. 
    if (audio.paused) {
        audio.play();
        document.getElementById('playbtn').innerHTML = "❚❚";
    } else {
        document.getElementById('playbtn').innerHTML = "▷";
        audio.pause();
    }

}

文档