我正在使用网络音频 API,我遇到了这个问题
描述:
我正在开发一个简单的网页,该网页使用 Web Audio API 通过频率滑块和播放/停止按钮生成声音。我面临的问题是“播放”按钮(
#playButton
)只能使用一次。第一次播放后,后续点击“播放”按钮不会发出任何声音。
这是我的代码的简化版本:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta tags -->
<title>Frequency Slider</title>
<!-- CSS styles -->
</head>
<body>
<label for="frequencySlider">Frequency:</label>
<input type="range" id="frequencySlider" min="20" max="2000" step="1" value="440">
<span id="frequencyDisplay">440 Hz</span>
<button id="playButton">Play</button>
<button id="stopButton">Stop</button>
<!-- Canvas for waveform visualization -->
<script>
// Web Audio API setup
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
let frequencyValue = 440;
let waveform = "sawtooth";
const osc = audioContext.createOscillator();
osc.type = waveform;
osc.frequency.value = frequencyValue;
const analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
const dataArray = new Uint8Array(analyser.fftSize);
// DOM elements
const frequencySlider = document.getElementById('frequencySlider');
const frequencyDisplay = document.getElementById('frequencyDisplay');
const playButton = document.getElementById('playButton');
const stopButton = document.getElementById('stopButton');
const canvasContext = waveformCanvas.getContext('2d'); // Assuming you have a canvas, if not, you can omit this
// Event listeners
frequencySlider.addEventListener('input', updateFrequency);
playButton.addEventListener('click', playSound);
stopButton.addEventListener('click', stopSound);
// Functions
function updateFrequency() {
frequencyValue = parseInt(frequencySlider.value);
osc.frequency.value = frequencyValue;
frequencyDisplay.textContent = frequencyValue + ' Hz';
}
function playSound() {
osc.connect(analyser);
analyser.connect(audioContext.destination);
osc.start(audioContext.currentTime);
requestAnimationFrame(drawWaveform);
}
function stopSound() {
osc.stop(audioContext.currentTime);
osc.disconnect(analyser);
analyser.disconnect(audioContext.destination);
canvasContext.clearRect(0, 0, waveformCanvas.width, waveformCanvas.height); // Assuming you have a canvas, if not, you can omit this
}
// Assuming you have a drawWaveform function, if not, you can omit this
function drawWaveform() {
analyser.getByteTimeDomainData(dataArray);
// Drawing logic for the waveform visualization
// ...
requestAnimationFrame(drawWaveform);
}
</script>
</body>
</html>
我注意到,单击“播放”按钮一次后,后续单击不会产生任何声音。我怀疑我处理 Web Audio API 或振荡器的方式可能存在问题。有人可以帮我弄清楚为什么“播放”按钮只能工作一次以及如何使其多次工作吗?
预先感谢您的协助!
您只能在振荡器上调用
start
一次。请参阅https://www.w3.org/TR/webaudio/#AudioScheduledSourceNode-methods。当您第二次按“播放”时,应该会出现控制台错误消息。
您需要做的是每次按下播放键时创建一个新振荡器。当您停止振荡器时,请务必删除对其的任何引用,以便可以收集它。您不需要将其与分析仪断开;当收集振荡器时,这应该会自动发生。