【问题标题】:Audio play/pause on different button click Jquery不同按钮上的音频播放/暂停单击Jquery
【发布时间】:2014-10-27 06:01:42
【问题描述】:

这是一个简单的查询,但不知怎的,我似乎无法确定似乎出了什么问题。

我有两个按钮,即“问题”和“需要”。单击前者时,需要播放音频文件 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。 我可以进行哪些更改才能使其正常工作?

【问题讨论】:

    标签: javascript jquery html audio


    【解决方案1】:

    我认为你的问题是这段代码:

     $("#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 版本。所以我认为您也可以像使用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。我希望这能让你朝着正确的方向开始。

    【讨论】:

    • 感谢分享有助于解决查询的 .attr 的正确语法。
    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 2019-03-01
    • 2022-12-11
    相关资源
    最近更新 更多