【发布时间】:2021-07-06 00:56:33
【问题描述】:
我来自 max/msp,并试图找出在优化我的代码/获得更好性能方面编程网络音频的最佳实践。
我正在阅读这样一个事实,即出于优化原因,不能在振荡器上调用 .start(),然后是 .stop(),然后是 .start()。如果我想制作一个简单的 1 振荡器合成器类,我想知道最好的设计模式是什么。
我想在需要播放之前实例化合成器。这样我想我会得到最好的时机,如果我想在以后播放合成器,所以系统不必在每次我点击“播放音符”时创建振荡器/合成器模式。
但是最好不要在我听不见的振荡器上使用处理能力,因为例如幅度包络未打开。
这是一个简单的合成器,没有振幅包络。我怎样才能做出类似的模式,只在合成器实际播放时才使用处理能力?
最好的,拉斯
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to optimize CPU usage</title>
</head>
<body>
<a href="#" id="playButton">Play Note</a> <br><br>
<a href="#" id="stopButton">Stop Note</a>
<script>
class Synth {
constructor () {
this.context = new AudioContext();
this.osc = this.context.createOscillator();
this.osc.connect(this.context.destination);
}
play(freq) {
this.osc.frequency.value = freq;
this.osc.start(0);
}
stop() {
this.osc.stop(0);
}
}
let synth = new Synth();
const playButton = document.getElementById('playButton')
.addEventListener('click', () => {synth.play(440)});
const stopButton = document.getElementById('stopButton')
.addEventListener('click', () => {synth.stop()});
</script>
</body>
</html>
【问题讨论】:
-
如果在你没有敲击一个音符时振荡器没有运行,你怎么知道它的相位?
-
这是个好问题。我来自 max/msp,那里有内置方法可以使用振荡器作为查找表并通过它来为您提供相位:)
标签: javascript performance html5-audio web-audio-api sound-synthesis