gpt4 book ai didi

javascript - Web音频API,使用panNode时出现问题,声音仅播放一次

转载 作者:行者123 更新时间:2023-12-03 00:24:08 24 4
gpt4 key购买 nike

我试图在一个小型测试应用程序中将某些声像效果整合到某些声音中。除一个重要问题外,它工作正常:每个声音只播放一次!
我尝试了几种方法来绕过该问题而没有成功。问题是,我无法确定问题的出处。这是我的代码,下面是一些解释。

const audio = new Audio('audio/background.mp3');
const footstep = new Audio('audio/footstep1.mp3');
const bumpWall1 = new Audio(`audio/bump-wall1.mp3`);
const bumpWall2 = new Audio(`audio/bump-wall2.mp3`);
const bumpWall3 = new Audio(`audio/bump-wall3.mp3`);
const bumpWall4 = new Audio(`audio/bump-wall4.mp3`);
const bumpWallArray = [bumpWall1, bumpWall2, bumpWall3, bumpWall4];

audio.volume = 0.5;

function play(sound, dir) {
let audioContext = new AudioContext();
let pre = document.querySelector('pre');
let myScript = document.querySelector('script');

let source = audioContext.createMediaElementSource(sound);

let panNode = audioContext.createStereoPanner();
source.connect(panNode);
panNode.connect(audioContext.destination);
if (dir === "left") {
panNode.pan.value = -0.8
} else if (dir === "right") {
panNode.pan.value = 0.8;
} else {
panNode.pan.value = 0;
}
sound.play();
}
因此,基本上,当您调用play()函数时,它会在左侧,右侧或中间播放声音。但是每个声音只能播放一次。例如,如果足迹已被播放一次,那么如果我在其上调用play()函数,它将永远不会再播放。
有人可以帮我吗?

最佳答案

developer console中,应该有一条消息,说明与

Uncaught InvalidStateError: Failed to execute 'createMediaElementSource' on 'AudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode.


(至少在Chrome中是这样),您不能多次将MediaElement连接到MediaElementSourceNode。
为了避免这种情况,您必须从MediaElementSourceNode断开此MediaElement的连接,但是 this isn't possible...
您所处的最佳状态可能是直接使用 AudioBuffers而不是HTMLAudioElements,此外,如果您没有将它们附加在文档中。

let audio;
const sel = document.getElementById( 'sel' );
// create a single AudioContext, these are not small objects
const audioContext = new AudioContext();
fetch( 'https://dl.dropboxusercontent.com/s/agepbh2agnduknz/camera.mp3' ).then( resp => resp.arrayBuffer() )
.then( buf => audioContext.decodeAudioData( buf ) )
.then( audioBuffer => audio = audioBuffer )
.then( () => sel.disabled = false )
.catch( console.error );

function play(sound, dir) {

let source = audioContext.createBufferSource();
source.buffer = sound;

let panNode = audioContext.createStereoPanner();
source.connect( panNode );
panNode.connect( audioContext.destination );
if (dir === "left") {
panNode.pan.value = -0.8
} else if (dir === "right") {
panNode.pan.value = 0.8;
} else {
panNode.pan.value = 0;
}
source.start( 0 );

}

sel.onchange = evt => play( audio, sel.value );
<select id="sel" disabled>
<option>left</option>
<option>center</option>
<option>right</option>
</select>

关于javascript - Web音频API,使用panNode时出现问题,声音仅播放一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62711164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com