Web音频api音频文件抽象只识别初始播放时的预定时间.然后它会立即回放

Web audio api audio file abstraction only recognizes the scheduled time on initial playback. It then plays back immediately

本文关键字:音频 然后 定时间 回放 播放 抽象 文件 api 识别 Web      更新时间:2023-09-26

下面代码的目标是确保每次事件侦听器被触发时,声音在未来2秒后播放。目前,这只在事件第一次被触发时起作用。所有随后的鼠标按下事件立即播放该文件。我正在寻找一个关于如何补救的提示。

var audioContext = new webkitAudioContext;
function AudioObj(fileDirectory) {
    var soundObj = {};
    soundObj.fileDirectory = fileDirectory;
    var getSound = new XMLHttpRequest();
    getSound.open("GET", soundObj.fileDirectory, true);
    getSound.responseType = "arraybuffer";
    getSound.onload = function() {
        audioContext.decodeAudioData(getSound.response, function(buffer) {
            soundObj.soundToPlay = buffer;
        });
    }
    getSound.send();

soundObj.play = function(time) {
        var playSound = audioContext.createBufferSource();
        playSound.buffer = soundObj.soundToPlay;
        playSound.connect(audioContext.destination);
        playSound.start(time );
      }
      return soundObj;
}

var snare = AudioObj("snare.mp3");
window.addEventListener("mousedown", go);
function go(){
    snare.play(2)
}

开始时间不是偏移量。你需要调用play sound.start(AudioContext)。currentTime + time);在play()方法中