javascript - 不同按钮上的音频播放/暂停单击 Jquery

标签 javascript jquery html audio

这是一个简单的查询,但不知怎的,我似乎无法指出哪里出了问题。

我有两个按钮,即“问题”和“需要”。单击前者时,需要播放音频文件 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">');

我刚刚浏览了 official documentation看来您使用 .attr 的方式不正确。我还没有尝试过我要发布的代码,但假设您确实想要设置 source 元素的属性,您可能需要尝试以下几行:

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

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

 $("#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。我希望这能让您朝着正确的方向开始。

关于javascript - 不同按钮上的音频播放/暂停单击 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26581920/

相关文章:

jquery - 如何通过window.scroll设置幻灯片切换

javascript - 我想要 jquery 可拖动脚本来记住位置

javascript - 在 href 旁边渲染 DIV

html - 如何将 <a> 放在 <li> 行的末尾

javascript - Angular JS : include partial HTML inside another ng-include

javascript - Node.js/Express.js 将 POST 请求转发到另一个域

javascript - 套接字 : data loss due to socket getting closed due to transport error

javascript - 如何让 Grunt/Watch/LiveReload 重新加载 Sass/CSS 而无需刷新整个页面?

javascript - Jquery 根据值添加元素

python - 从 html 表单中获取整数