Javascript在没有音频崩溃的情况下播放音频

时间:2015-03-17 15:22:52

标签: javascript html5 audio

我正在尝试使用Javascript播放一个接一个音频。我从vector(int)和我创建的一些字符串中获取音频文件名。 这是我的代码,但我不能使它有效。

var audio = new Audio();
function playAll(){
    var folder_name = "synthex/";
    var file_name = ".sentence"; 
    var audio_file = ".wav";

    for(i=0;i<18;++i)
    {   
    var dir_file = folder_name + voicesClicks[i];
    dir_file = dir_file + file_name;

    if(voicesClicks[i] == null){
        continue;
    }
    //var value = voicesClicks[i];

    dir_file = dir_file + i;
    dir_file = dir_file + audio_file;

    console.log(dir_file);

    audio.src = dir_file;
    audio.play();

    }
}

1 个答案:

答案 0 :(得分:1)

我在代码中发现的一个主要问题是,audio src在每次迭代中都在不断变化,所以即使audio.src值是vaild wav文件,你也会编码最后玩最后一个...

我有类似的要求,我做了......

&#13;
&#13;
function playAll() {
  // CHANGE this list to as per your requirement.
  var urls = ['http://upload.wikimedia.org/wikipedia/en/f/f9/Beatles_eleanor_rigby.ogg',
    'http://upload.wikimedia.org/wikipedia/commons/5/5b/Ludwig_van_Beethoven_-_Symphonie_5_c-moll_-_1._Allegro_con_brio.ogg'
  ];
  var idx = 0;
  var aud = new Audio();
  aud.src = urls[idx];
  aud.addEventListener('ended', function() { // for automatically starting the next.
    idx++;
    if (idx === urls.length) idx = 0;
    aud.src = urls[idx];
    aud.play();
  });
  aud.play();
}

document.addEventListener("DOMContentLoaded", playAll); // you can change this to button.onclick handler.
&#13;
&#13;
&#13;

修改:您可以将urls更改为...

var urls = [];
for(i=0;i<18;++i){
    if(!voicesClicks[i]){
        continue;
    }
    urls.push(folder_name + voicesClicks[i] + file_name + i + audio_file);
}
console.log(JSON.stringify(urls));  // for debug