创建无缝的音频循环 - Web

mar*_*ice 5 javascript audio html5 html5-audio web-audio-api

我想创建一个音频文件的无缝循环.但到目前为止我使用的所有方法中,结束与开始之间存在明显的差距.


这是我到目前为止所尝试的:

第一种方法是使用HTML中的音频并且循环但是从轨道的末尾开始到开始时仍然存在明显的延迟.

<audio loop autoplay>
    <source src="audio.mp3" type="audio/mpeg">
<audio>
Run Code Online (Sandbox Code Playgroud)

然后我用JavaScript尝试了相同的结果:

let myAudio = new Audio(file);
myAudio.loop = true; 
myAudio.play();
Run Code Online (Sandbox Code Playgroud)

之后我尝试了这个(根据这个答案)

myAudio.addEventListener(
    'timeupdate',
    function() {
        var buffer = .44;
        if (this.currentTime > this.duration - buffer) {
            this.currentTime = 0;
            this.play();
        }
     },
     false
);
Run Code Online (Sandbox Code Playgroud)

我玩缓冲区但我只是为了缩小差距而不是完全放弃它.

我转向库SeamlessLoop(GitHub)并让它在Chromium浏览器中无缝循环(但不是在最新的Safari中.没有在其他浏览器中测试).我用的代码:

let loop = new SeamlessLoop();
// My File is 58 Seconds long. Btw there aren't any gaps in the file.
loop.addUri(file, 58000, 'sound1');
loop.callback(soundsLoaded);
function soundsLoaded() {
    let n = 1;
    loop.start('sound' + n);
}
Run Code Online (Sandbox Code Playgroud)

编辑:我尝试了另一种方法:通过两个不同的音频元素循环:

var current_player = "a";
var player_a = document.createElement("audio");
var player_b = document.createElement("audio");

player_a.src = "sounds/back_music.ogg";
player_b.src = player_a.src;

function loopIt(){
    var player = null;

    if(current_player == "a"){
        player = player_b;
        current_player = "b";
    }
    else{
        player = player_a;
        current_player = "a";
    }

    player.play();

    /*
        3104.897 is the length of the audio clip in milliseconds.
        Received from player.duration. 
        This is a different file than the first one
    */
    setTimeout(loopIt, 3104.897); 
}

loopIt();
Run Code Online (Sandbox Code Playgroud)

但是,由于浏览器中的毫秒数不够一致或不够精细,这不能很好地工作,但它确实比音频的正常"循环"属性好得多.


任何人都可以引导我走向正确的方向来无缝循环音频吗?

小智 7

您可以改用Web Audio API。对此有几个注意事项,但它可以让您准确地循环到单个样本级别。

需要注意的是,您必须将整个文件加载到内存中。这对于大文件可能不切实际。如果文件只有几秒钟,则应该没有任何问题。

第二个是您必须手动编写控制按钮(如果需要),因为 API 具有低级方法。这意味着播放、暂停/停止、静音、音量等。扫描和可能的暂停本身就是一个挑战。

最后,并非所有浏览器都支持 Web Audio API - 在这种情况下,您将不得不回退到常规音频 API 甚至 Flash,但如果您的目标是现代浏览器,这现在应该不是主要问题。

例子

这将加载一个 4 小节鼓循环,并在循环时没有任何间隙地播放。主要步骤是:

  • 它从启用 CORS 的源加载音频(这很重要,要么使用与您的页面相同的域,要么设置外部服务器以允许跨域使用,就像 Dropbox 在本例中为我们所做的那样)。
  • AudioContext 然后解码加载的文件
  • 解码后的文件用于源节点
  • 源节点连接到输出
  • 启用循环并从内存中播放缓冲区。

var actx = new (AudioContext || webkitAudioContext)(),
    src = "https://dl.dropboxusercontent.com/s/fdcf2lwsa748qav/drum44.wav",
    audioData, srcNode;  // global so we can access them from handlers

// Load some audio (CORS need to be allowed or we won't be able to decode the data)
fetch(src, {mode: "cors"}).then(function(resp) {return resp.arrayBuffer()}).then(decode);

// Decode the audio file, then start the show
function decode(buffer) {
  actx.decodeAudioData(buffer, playLoop);
}

// Sets up a new source node as needed as stopping will render current invalid
function playLoop(abuffer) {
  if (!audioData) audioData = abuffer;  // create a reference for control buttons
  srcNode = actx.createBufferSource();  // create audio source
  srcNode.buffer = abuffer;             // use decoded buffer
  srcNode.connect(actx.destination);    // create output
  srcNode.loop = true;                  // takes care of perfect looping
  srcNode.start();                      // play...
}

// Simple example control
document.querySelector("button").onclick = function() {
  if (srcNode) {
    srcNode.stop();
    srcNode = null;   
    this.innerText = "Play";
  } else {
    playLoop(audioData);
    this.innerText = "Stop";
  }
};
Run Code Online (Sandbox Code Playgroud)
<button>Stop</button>
Run Code Online (Sandbox Code Playgroud)