播放由jquery更改的新音频源

时间:2012-03-07 14:43:29

标签: jquery audio html5-audio audio-player

大家

我写了简单的音乐播放器,但我有一个问题。我使用ajax从文件php获取新的源代码并且工作正常,但我不知道如何播放新歌。简单的audio.play()不起作用。我尝试修复这是我的代码:

    function timer(){
    timeleft = $("span#timeleft");
    slider = $("div#slider");
    $(audio).bind('timeupdate', function(){
        var rem = parseInt(audio.duration - audio.currentTime, 10),
        pos = (audio.currentTime / audio.duration) * 315,
        mins = Math.floor(rem/60, 10),
        secs = rem - mins*60;

        timeleft.text('- ' + mins + ':' + (secs > 9 ? secs : '0' + secs));
        slider.css({width: pos + 'px'});
    });
}

$(document).ready(function(){
    audio = $("audio#audio-player-header").get(0);

    $("div#controls").click(function(){
        $(this).toggleClass("pause");
        if(audio.paused){
            audio.play();
            timer();
        }else{
            audio.pause();
        }
    });

    audio.addEventListener("ended", function(){
            $.post("php/player.php", function(result){
                audio.src = result;
            });
            audio.play(); // here is the problem
            timer();
    });
});

和HTML:

<div id="player">
                    <div id="controls" class="play"></div>
                    <div id="music-title">
                        <div id="slider">
                            <div id="wrap-music-title">
                                <p id="music-title">Jamie T - Chaka Demus</p>
                            </div>
                        </div>
                    </div>
                    <span id="timeleft"></span>
                    <div id="player-header">
                    <audio id="audio-player-header" src="music/rock/Jamie T - Chaka Demus.mp3">
                    </audio>
                    </div>
                </div>

我在stackoverflow和web上找到了一些解决方案,但这里没有任何作用。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您创建了一个竞争条件,在您调用ajax之前调用audio.play()。您可以(A)听取音频canplay事件然后触发播放或(B)只设置音频标签的autoplay属性。

选项A:

audio.addEventListener("ended", function(){
    $.post("php/player.php", function(result){
        audio.src = result;
    });
});

audio.addEventListener("canplay", function(){
    audio.play();
});

选项B:

<audio autoplay id="audio-player-header" src="music/rock/Jamie T - Chaka Demus.mp3">