gpt4 book ai didi

javascript - WebAudio 在开始和结束时播放声音

转载 作者:行者123 更新时间:2023-11-30 11:26:07 25 4
gpt4 key购买 nike

每当我使用如下代码播放声音时

// binaryData = a wave file from a websocket
let ctx = new AudioContext();
ctx.decodeAudioData(binaryData, function(audioData){
let source = ctx.createBufferSource();
source.buffer = audioData;
source.connect(ctx.destination);
source.start(0);
});

播放的每个剪辑之间都有非常明显的咔哒声或爆裂声。忘记我正在尝试使用该系统播放实时音频这一事实;为什么在播放的每个声音片段的开头和结尾都有杂音?我不明白这是 2017 年音频播放设备可接受的行为......有什么办法可以减轻或消除这种情况吗?


回答

下面的答案后面是一组很好的 #s,可用于将点击次数减少到基本为零。我并不是说这对音调非常有用,但它对声音来说是完美无缺的。

// start of clip
// clipPlayTime may be 0 or your scheduled play time
gain.setValueAtTime(0.01, clipPlayTime);
gain.exponentialRampToValueAtTime(1, clipPlayTime + 0.001);
// end of clip
gain.setValueAtTime(1, clipPlayTime + clipLength - 0.001);
gain.exponentialRampToValueAtTime(0.01, clipPlayTime + clipLength);

这会产生上升和下降。

最佳答案

使用 exponentialRampToValueAtTime()消除(或至少减少)咔嗒声。

这是一个很好的解释:Web Audio, the ugly click and the human ear


完整示例

基本示例取自:https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/decodeAudioData

<button class="play">Play</button>
<button class="stop">Stop</button>

<script type="text/javascript">
var audioCtx = new(window.AudioContext || window.webkitAudioContext)();
var source;
var play = document.querySelector('.play');
var stop = document.querySelector('.stop');
var gainNode = audioCtx.createGain();


function getData() {
source = audioCtx.createBufferSource();
var request = new XMLHttpRequest();
request.open('GET', './sample.wav', true);
request.responseType = 'arraybuffer';
request.onload = function() {
var audioData = request.response;

audioCtx.decodeAudioData(audioData, function(buffer) {
source.buffer = buffer;
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
gainNode.gain.setValueAtTime(1, audioCtx.currentTime);
},

function(e) {
console.log("Error with decoding audio data" + e.err);
});
}
request.send();
}


play.onclick = function() {
getData();
source.start(0);
play.setAttribute('disabled', 'disabled');
}

stop.onclick = function() {
gainNode.gain.setValueAtTime(gainNode.gain.value, audioCtx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + 1);
setTimeout(function() {
source.stop();
}, 1000)
play.removeAttribute('disabled');
}
</script>

关于javascript - WebAudio 在开始和结束时播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47996114/

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