为什么我的第二个音频文件不能使用 currentTime 属性 播放?

Why does my second audio file not play using the currentTime property?

我希望我的 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);

如果您真的希望它及时准确,则不能使用 Audio() - 那是 HTML5

您必须使用音频 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