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

时间:2018-10-04 04:45:07

标签: javascript html5 audio audio-streaming web-audio

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

2 个答案:

答案 0 :(得分:1)

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

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


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

通过thi方法,您可以追加两个缓冲区:

 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

答案 1 :(得分:0)

如果您确实希望时间上的准确性,则不能使用Audio()-这是HTML5