javascript - 为什么我的第二个音频文件无法使用 currentTime 属性播放?

标签 javascript html audio audio-streaming web-audio-api

我希望我的audio2 文件在audio1.currentTime 为3 秒时播放,但我无法使其工作。我是 javascript 的新手,我错过了什么?这是我当前的 JavaScript 代码:

    function initAudioPlayer(){
            var audio1, audio2, ext, agent;

            ext = ".mp3";
            agent = navigator.userAgent.toLocaleLowerCase();

            if(agent.indexOf('firefox') != -1 || agent.indexOf('opera') != -1) { ext = ".ogg";}


//Audio Objects: audio1 and audio2

            audio1 = new Audio();
            audio1.src = "folder/Audio1"+ext;
            audio1.loop = false;
            audio1.play();

            audio2 = new Audio();
            audio2.src = "folder/Audio2"+ext;
            audio2.loop = false;
            audio2.play();

//Function that reproduces the second audio file at second 3 of the first audio file

    function audio2(){
            if(audio1.currentTime == 3) {audio2.play();}
        };    
    }

    window.addEventListener("load", initAudioPlayer);

最佳答案

您必须使用音频 Api 并获取文件的缓冲区。 然后您必须加上每个字节并复制到另一个新缓冲区。 这段代码可以帮助你:

let idnex=0;
    samples.forEach(buufer => {


      if (index === 0) {
        tempBuf = buufer;
      } else {
        tempBuf = this.appendBuffer(tempBuf, buufer);
      }
      index++;
    });

通过这种方法,您可以附加两个缓冲区:

 private appendBuffer(buffer1, buffer2) {


const numberOfChannels = Math.min(buffer1.numberOfChannels, buffer2.numberOfChannels);
const tmp = this.audioContextService.createBuffer(Math.max(buffer1.numberOfChannels, buffer2.numberOfChannels),
  Math.max(buffer1.length, buffer2.length), buffer1.sampleRate);

for (let i = 0; i < numberOfChannels; i++) {

  const channel = tmp.getChannelData(i);
  let finallArray = [];
  let d = [];
  const chanelTemp = buffer1.getChannelData(i);


  if (buffer2.numberOfChannels <= i) {

    finallArray = chanelTemp;
  } else {
    const c = buffer2.getChannelData(i);
    if (chanelTemp.length > c.length) {

      finallArray = chanelTemp;
      d = c;
    } else {

      finallArray = c;
      d = chanelTemp;
    }

    for (let j = 0; j < d.length; j++) {

      finallArray[j] += d[j] / 2;


    }

  }


  channel.set(finallArray, i);

}

你可以看我的演示here

<小时/>

您还可以看到this Answer

关于javascript - 为什么我的第二个音频文件无法使用 currentTime 属性播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52639176/

相关文章:

javascript - 如何将 ng-include 回调添加到 Angular js 中的多个 ng-include 指令

iphone - 当发生中断时如何让我的音频应用程序在后台保持事件状态?

javascript - 在使用 iOS Phonegap 包装的 jQuery Mobile 中找不到具有相对 src 的图像

html - 我怎样才能使这个仅 CSS 的轮播默认显示第一张幻灯片?

Android 和声音处理?

audio - 确定音频文件是否以Apple Lossless(ALAC)编码

javascript - 如何动态更改 Bootstrap 模态主体

javascript - 同步幻灯片放映的 jQuery setInterval

javascript - 为什么很少有日期格式在 javascript 中不起作用

javascript - TinyMCE 从可视选项卡上的链接中剥离 JavaScript