2

我想播放一个单词列表。每个单词都由该单词在三种不同方言中的录音表示。对于每个单词,所有三个音频文件都应该同时开始播放。下面的代码在大多数情况下都有效,但有时三个音频文件对于给定单词的播放会不同步。为什么会这样,我该如何解决?

更新: 我认为问题是音频必须被获取并存储在客户端机器上的某种缓存中。至少这是我的结论,因为我注意到当新词添加到播放列表时问题更加普遍。我可以在开始播放之前缓存所有单词的所有音频吗?

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Player</title>

<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){

var _dialects = ["c","m","u"];

var _playlist = 
[
    "ta_x", 
    "me_x", 
    "ag",
    "rith",
    "agus",
    "ag",
    "ceol",
];

var _players = new Array(); 
for (var i=0;i<_dialects.length;i++)
{
    _players[i] = document.getElementById("audio_player_"+(i+1));
}

var _number_of_available_players = _dialects.length;
var _playlist_index = 0;

var _play_button = document.getElementById("play_button");

function play()
{
    _playlist_index = 0;
    _play_button.disabled  = true;
    next();
}

function next()
{
    if(_number_of_available_players == _dialects.length)
    {
        if(_playlist_index < _playlist.length)
        {
            for (var i=0;i<_players.length;i++)
            {
                if (_players[i].canPlayType('audio/mpeg;')) 
                {
                    _players[i].src = "http://www.focloir.ie/media/ei/sounds/" + _playlist[_playlist_index] + "_"+_dialects[i]+".mp3";
                }
                else
                {
                    _players[i].src = "http://www.focloir.ie/media/ei/sounds_ogg/" + _playlist[_playlist_index] + "_"+_dialects[i]+".ogg";
                }
                _players[i].play();
            }
            _playlist_index = _playlist_index + 1;
            _number_of_available_players = 0;
        }
        else
        {
            _play_button.disabled  = false;
        }
    }
}

function end()
{
    _number_of_available_players = _number_of_available_players + 1
    next();
}

for (var i=0;i<_players.length;i++)
{
    _players[i].addEventListener('ended', end);
}
_play_button.addEventListener('click', play);

}//]]>  

</script>
</head>

<body>
    <audio id = "audio_player_1"></audio>
    <audio id = "audio_player_2"></audio>
    <audio id = "audio_player_3"></audio>
    <button id = "play_button">Play</button>
</body>
</html>
4

0 回答 0