Mah*_*koe 5 javascript audio web
假设您使用Web Audio API来播放纯音:
ctx = new AudioContext();
src = ctx.createOscillator();
src.frequency = 261.63; //Play middle C
src.connect(ctx.destination);
src.start();
Run Code Online (Sandbox Code Playgroud)
但是,后来您决定停止声音:
src.stop();
Run Code Online (Sandbox Code Playgroud)
从现在开始,src现在完全没用了;如果您尝试再次启动它,您会得到:
src.start()
VM564:1 Uncaught DOMException: Failed to execute 'start' on 'AudioScheduledSourceNode': cannot call start more than once.
at <anonymous>:1:5
Run Code Online (Sandbox Code Playgroud)
比如说,如果您正在制作一个小型在线键盘,您就会不断地打开和关闭音符。从音频节点图中删除旧对象,创建一个全新的对象,然后connect()将其放入图中(然后稍后丢弃该对象)似乎非常笨重,而在需要时打开和关闭它会更简单。
Web Audio API 这样做有什么重要原因吗?或者是否有一些更干净的方法来重新启动音频源?
使用connect()和disconnect(). 然后您可以更改任何值AudioNode来更改声音。
(该按钮是因为AudioContext需要用户操作才能在代码片段中运行。)
play = () => {
d.addEventListener('mouseover',()=>src.connect(ctx.destination));
d.addEventListener('mouseout',()=>src.disconnect(ctx.destination));
ctx = new AudioContext();
src = ctx.createOscillator();
src.frequency = 261.63; //Play middle C
src.start();
}Run Code Online (Sandbox Code Playgroud)
div {
height:32px;
width:32px;
background-color:red
}
div:hover {
background-color:green
}Run Code Online (Sandbox Code Playgroud)
<button onclick='play();this.disabled=true;'>play</button>
<div id='d'></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
677 次 |
| 最近记录: |