如何在howler.js上链接声音

时间:2014-09-29 17:25:54

标签: javascript howler.js

我需要在howler.js中播放一些声音,我不知道如何链接它。

例如,字符串BCG

需要播放b.ogg然后是c.ogg,最后是g.ogg

如果我只是使用(加载后):

sound.play('b');
sound.play('c');
sound.play('g');

所有这些都是开始和重叠,这不是我需要的。

我看到有一个属性,但无法弄清楚如何正确使用它。

问候。

3 个答案:

答案 0 :(得分:4)

您可以创建一个函数playString(yourString),它将读取每个字符并动态设置声音的onend属性。以下示例应播放 B C G A C

var sound = new Howl({
    urls: ['http://shrt.tf/abcdefg.mp3'],
    volume: 1,
    sprite: {
        a: [0, 600],
        b: [700, 500],
        c: [1200, 600],
        d: [1900, 500],
        e: [2400, 500],
        f: [2900, 500],
        g: [3400, 500],
    }
});

Howl.prototype.playString = function(str){
    if(str.length>1){
        this._onend[0] = function(){this.playString(str.substring(1,str.length));};
    } else {
        this._onend[0] = function(){};
    }
    if(str.length>0){
        this.play(str.substring(0,1));
    }
};

sound.playString('bcgac');
<script src="http://shrt.tf/howler.js"></script>

请注意,您也可以调整此函数,以便在角色不在精灵中时使用,或者使用名称数组而不是字符串。

答案 1 :(得分:3)

您可以使用此代码,不需要精灵(jsfiddleGithub issue):

var playlist = function(e) {
    // initialisation:
      pCount = 0;
      playlistUrls = [
        "https://upload.wikimedia.org/wikipedia/commons/8/8a/Zh-Beijing.ogg",
        "https://upload.wikimedia.org/wikipedia/commons/8/8a/Zh-Beijing.ogg",
        "./audio/a.mp3",
        "./audio/b.mp3",
        "./audio/c.mp3",
        "./audio/d.mp3"
        ], // audio list
      howlerBank = [],
      loop = true;

    // playing i+1 audio (= chaining audio files)
    var onEnd = function(e) {
      if (loop === true ) { pCount = (pCount + 1 !== howlerBank.length)? pCount + 1 : 0; }
      else { pCount = pCount + 1; }
      howlerBank[pCount].play();
    };

    // build up howlerBank:     
    playlistUrls.forEach(function(current, i) {   
      howlerBank.push(new Howl({ urls: [playlistUrls[i]], onend: onEnd, buffer: true }))
    });

    // initiate the whole :
        howlerBank[0].play();
}

如果你做的话,请分享你的变化。

答案 2 :(得分:2)

这是我的简单解决方案,我使用的是小文件,因此下载延迟不是问题。在这种情况下声音是全局的

function play_audio(file_names) {
    sound = new Howl({
        src: [audio_url+file_names[0]],
        volume: 0.5,
        onend: function() {
            file_names.shift();
            if (file_names.length > 0) {
                play_audio(file_names);
            }
        }
    });      
    sound.play();
}