如何在howler.js上链接声音

How to chain sounds on howler.js

本文关键字:链接 声音 js howler      更新时间:2023-09-26

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

例如,在字符串BCG

需要玩b.ogg,然后玩c.ogg,最后玩g.ogg

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

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

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

我看到有一个单一的属性,但是我不知道如何正确使用它。

谨致问候。

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

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();
}

您可以在不需要精灵的情况下使用此代码(jsfiddle,Github问题):

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();
}

如果你做了一个,请分享你的变体。

您可以创建一个函数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>

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

一个接一个地链接音频的简单解决方案。代码也不会为列表中的每个音频文件创建一个新的Howl实例。我在这里使用音频精灵。

const playSounds = (_audioList) => {
let sound = new Howl({
  src: ["/effects/effects.webm", "/effects/effects.mp3"],
  sprite: {
    a: [5000, 3648.004535147393],
    b: [14000, 2832.0181405895682],
    c: [57000, 2712.0181405895705],
  },
});
sound.play(_audioList.shift());
sound.on("end", () => {
  _audioList.length > 0 && sound.play(_audioList.shift());
});
playSounds(["a", "b", "c"];