音频播放/暂停不同按钮单击Jquery

Audio play/pause on different button click Jquery

本文关键字:按钮 单击 Jquery 播放 暂停 音频      更新时间:2023-09-26

这是一个简单的查询,但不知何故,我似乎无法指出问题所在。

我有两个按钮,即"问题"answers"需要"。在点击前者时,需要播放音频文件1,类似地,当稍后点击时,音频文件1应该停止并且播放音频文件2。我写的代码是这样的:

var playing = false;
$("#problem").click(function(event) {
    $("#audio").html('');
    $("#audio").html('<source src="audio/expertise/file1.mp3" type="audio/mp3"><source src="audio/expertise/file1.wav" type="audio/x-wav"><source src="audio/expertise/file1.ogg" type="audio/ogg">');
    playing = true;
});
$('.need_btn').attr('id', 'need_btn');
$("#need_btn").click(function(event) {
    if (playing == true) {
        $("#audio").trigger('pause');
        playing = false;
        if (playing == false){
            $("#audio").attr('src','<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');
            $("#audio").trigger('play');
            playing = true;
        };
    }
    else{
        /*$("#audio").trigger('play');*/
        };
});

这适用于播放文件1,当点击第二个按钮时暂停文件1,但不播放文件2。我可以更改什么以使其工作?

我认为您案例中的问题是这段代码:

 $("#audio").attr('src','<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');

我刚刚浏览了官方文档,似乎您使用.attr的方式不正确。我还没有尝试过我将要发布的代码,但假设您确实想设置source元素的属性,您可能想在以下行中尝试一些东西:

 $( "source" ).attr({
 src: "audio/expertise/file2.mp3",
 type: "audio/mp3"
 });

现在我知道您有.ogg.wav.mp3版本。因此,我认为也可以像使用file1一样,直接为id为"audio"的元素设置html。我建议这样做:

 $("#audio").html('<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');

这将为具有所需标记的相应元素设置html。我希望这能让你朝着正确的方向开始。