AudioParam: setValueAtTime() 方法
AudioParam 接口的 setValueAtTime() 方法会在精确的时间点安排 AudioParam 值的即时更改,该时间点相对于 AudioContext.currentTime 进行测量。新值在 value 参数中给出。
语法
js
setValueAtTime(value, startTime)
参数
value-
一个浮点数,表示 AudioParam 在给定时间将更改到的值。
startTime-
一个双精度浮点数,表示值更改将发生的
AudioContext首次创建后的时间(以秒为单位)。如果时间小于AudioContext.currentTime,则更改会立即发生。如果此值为负数,则会引发TypeError。
返回值
对该 AudioParam 对象的引用。在某些浏览器中,此接口的旧实现会返回 undefined。
示例
这个简单的示例包含一个媒体元素源和两个控制按钮(有关源代码,请参阅我们的 webaudio-examples 仓库,或在线查看示例)。按下按钮时,currGain 变量会增加/减少 0.25,然后使用 setValueAtTime() 方法将增益值设置为等于 currGain,时间在 1 秒后(audioCtx.currentTime + 1)。
js
// create audio context
const audioCtx = new AudioContext();
// set basic variables for example
const myAudio = document.querySelector("audio");
const pre = document.querySelector("pre");
const myScript = document.querySelector("script");
pre.textContent = myScript.textContent;
const targetAtTimePlus = document.querySelector(".set-target-at-time-plus");
const targetAtTimeMinus = document.querySelector(".set-target-at-time-minus");
// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);
// Create a gain node and set its gain value to 0.5
const gainNode = audioCtx.createGain();
gainNode.gain.value = 0.5;
let currGain = gainNode.gain.value;
// connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
// set buttons to do something onclick
targetAtTimePlus.onclick = () => {
currGain += 0.25;
gainNode.gain.setValueAtTime(currGain, audioCtx.currentTime + 1);
};
targetAtTimeMinus.onclick = () => {
currGain -= 0.25;
gainNode.gain.setValueAtTime(currGain, audioCtx.currentTime + 1);
};
规范
| 规范 |
|---|
| Web Audio API # dom-audioparam-setvalueattime |
浏览器兼容性
加载中…