【问题标题】:Why does js oscillators stop playing sound after some use?为什么js振荡器在使用后停止播放声音?
【发布时间】:2020-08-15 20:22:11
【问题描述】:

我正在尝试用 js 制作一个简单的钢琴,但我不想使用音频样本,而是想以编程方式生成声音。要播放单个声音,我正在使用此博客中的此代码 https://marcgg.com/blog/2016/11/01/javascript-audio/

var context = new AudioContext()
var o = context.createOscillator()
var  g = context.createGain()
o.connect(g)
g.connect(context.destination)
o.start(0)
g.gain.exponentialRampToValueAtTime(0.00001, context.currentTime + 5)

我发现在玩了大约 50 次之后,这个方法就失效了。运行此代码时没有声音播放,context.currentTime 不会改变并保持为 0。如何在不停止播放声音的情况下修复它?

【问题讨论】:

标签: javascript google-chrome audio


【解决方案1】:

不要为每条笔记创建一个新的AudioContext;创建一个并将其用于所有人。这不仅会节省资源;如果您决定要这样做,它还有助于在精确的时间演奏多个音符。

您还在积累仍在播放的振荡器,只是非常安静。你需要在某个时候阻止他们。好消息是,Web Audio API 设计为make it easy to do this:

// stop after 5 seconds from now
o.stop(context.currentTime + 5);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多