如何检测我的音频流是:播放,暂停还是已完成?

时间:2016-05-06 13:31:31

标签: javascript html html5-audio audio-streaming

我正在开设一个在线广播网站,并试图检测音频播放器当前为用户提供的状态。

我目前的设置通常是错误的,因为我知道这个,如果我在iOS上,而我从锁定屏幕播放器暂停,它仍会认为它正在播放,因为我从未点击过html暂停按钮。

最后,如何检测我的流何时完全结束。我尝试过:onstalled=""onwaiting=""onerror=""onended=""。但它们都没有100%的工作时间。最接近工作的是:onstalled="",但即便只有60%左右的成功率(偶尔当我加载网站时它会告诉我它已经结束)。

HTML:

<audio autoplay="" id="player" title="" oncanplay="radioLoaded()">
    <source src="...">
</audio>

使用Javascript:

function radioLoaded() {
    if (player.paused) {
        document.getElementById('radioplaypause').innerHTML = varRadioResume;
    } else if (player.play) {
        document.getElementById('radioplaypause').innerHTML = varRadioPause;
    } else {
        document.getElementById('radioplaypause').innerHTML = varRadioLoading;
    }

    window.player = document.getElementById('player');
    document.getElementById('radioplaypause').onclick = function () {
        if (player.paused) {
            player.play();
            this.innerHTML = varRadioPause;
        } else {
            player.pause();
            this.innerHTML = varRadioResume;
        }
    }
};

function radioEnded() { 
    document.getElementById('radiolivetext').innerHTML = 'OFFLINE';
    document.getElementById('radioplayer').style.display = 'none';
    document.getElementById('radioinformation').style.display = 'none';
};

1 个答案:

答案 0 :(得分:0)

尝试这一点,对代码进行一些更正/注释:

function radioLoaded() {

    // move this line to the top
    window.player = document.getElementById('player'); // !!! <-- name too generic, possibility of global collisions

    var playPauseButton = document.getElementById('radioplaypause');

    if (player.paused) {
        playPauseButton.innerHTML = varRadioResume;
    } else if (player.play) {
        playPauseButton.innerHTML = varRadioPause;
    } else {
        playPauseButton.innerHTML = varRadioLoading;
    }

    playPauseButton.onclick = function () {
        if (player.paused) {
            player.play();
            this.innerHTML = varRadioPause;
        } else {
            player.pause();
            this.innerHTML = varRadioResume;
        }
    };

    player.onended = function () {
        console.log('ended');
    };

    // other helpful events
    player.onpause = function () {
       console.log('paused...');
    }

    player.onplay = function () {
       console.log('playing...');
    }

    player.onprogress = function (e) {
       console.log(e.loaded + ' of ' + e.total + ' loaded');
    }
};