如何在Javascript中删除音轨之间的暂停

Mar*_*ngh 8 javascript audio

我正在构建一个javascript游戏,我想基于声音文件片段创建背景音乐.短mp3文件将它们作为一个连续的轨道播放.我已尝试在音频文件上绑定"已结束"事件处理程序,但这会导致音频片段之间出现延迟.

为了解决这个问题,我提出了一个仍然不起作用的hacky解决方案,在完成之前1秒更改音频.

Ebuc.manageAudio = function(){
    var listener = function (event) {
         if (this.currentTime > (this.duration - 1) && Ebuc.bgnext) {
             Ebuc.manageAudio();
             console.log("aduio");
             Ebuc.bgnext = false;
         }
         if(this.currentTime < 2){
            Ebuc.bgnext = true;
             console.log("reset");
         }
        console.log(event);
        console.log("listener active")

    };
    var color = Level.current.color;
    if(Ebuc.bgsong == null) {
        Ebuc.bgsong = new Audio('assets/sound/' + Resources.audioSetList[color].getcurrentsong());
        Ebuc.bgsong.addEventListener('timeupdate', listener, true);

    }
    else{
        Ebuc.bgsong = new Audio('assets/sound/' + Resources.audioSetList[color].getcurrentsong());
    }

    Ebuc.bgsong.play();
    Resources.audioSetList[color].next();

};
Run Code Online (Sandbox Code Playgroud)

此示例有效一次,当需要将片段2切换到片段3时,循环停止.记录事件监听器的控制台在停止之前给出4次日志.

Q1:为什么这个eventlistener突然消失了?Q2:是否存在用于链接这些音频片段的非黑客解决方案.

我提前谢谢你.

pan*_*nes 7

你不仅要暂停试图在两个短音频片段之间快速切换的问题,你可能想要快速地在两个音轨之间交叉淡入淡出以防止任何弹出,伪像等.

这是一个使用Howler的github问题进行交叉淡化的示例.您可以使用此示例,并保持已加载实例的队列以转换为.我希望有所帮助.

//you'll probably want this crossfade duration to be shorter.
var crossfadeDuration = 5000,
    volume            = 0.7;

var instance1, instance2, soundDuration;

// Singleton helper to build similar instances
var createHowlerInstance = function (urls, onload) {
  return new Howl({
    urls: urls,
    loop: false,
    volume: 0,
    onload: onload
  });
};

// Create "slave" instance. This instance is meant
// to be played after the first one is done.
instance2 = createHowlerInstance(['file2.mp3']);

// Create "master" instance. The onload function passed to
// the singleton creator will coordinate the crossfaded loop
instance1 = createHowlerInstance(['file1.mp3'], function(){

  // Get the sound duration in ms from the Howler engine
  soundDuration = Math.floor(instance1._duration * 1000);

  (function crossfadedLoop(enteringInstance, leavingInstance){

    // Fade in entering instance
    enteringInstance.pos(0).play().fade(0, volume, crossfadeDuration);

    // Wait for the audio end to fade out entering instance
    // white fading in leaving instance
    setTimeout(function(){

      enteringInstance.fade(volume, 0, crossfadeDuration);
      crossfadedLoop(leavingInstance, enteringInstance);

    }, soundDuration - crossfadeDuration);

  })(instance1, instance2);

});
Run Code Online (Sandbox Code Playgroud)