OfflineAudioContext
Baseline 广泛可用 *
OfflineAudioContext 接口是一个 AudioContext 接口,它代表一个由链接在一起的 AudioNode 构建的音频处理图。与标准的 AudioContext 不同,OfflineAudioContext 不会将音频渲染到设备硬件;相反,它会尽快生成音频,并将结果输出到 AudioBuffer。
构造函数
OfflineAudioContext()-
创建一个新的
OfflineAudioContext实例。
实例属性
还继承了其父接口 BaseAudioContext 的属性。
OfflineAudioContext.length只读-
一个整数,表示缓冲区中样本帧的大小。
实例方法
还继承了其父接口 BaseAudioContext 的方法。
OfflineAudioContext.suspend()-
在指定的将来时间点调度暂停音频上下文中的时间进程,并返回一个 Promise。
OfflineAudioContext.startRendering()-
开始渲染音频,考虑当前的连接和当前计划的更改。本页面同时涵盖基于事件的版本和基于 Promise 的版本。
已废弃的方法
OfflineAudioContext.resume()-
恢复先前已暂停音频上下文中时间的进程。
注意: resume() 方法仍然可用——它现在定义在 BaseAudioContext 接口上(请参阅 AudioContext.resume),因此 AudioContext 和 OfflineAudioContext 接口都可以访问它。
事件
使用 addEventListener() 或通过将事件监听器分配给此接口的 oneventname 属性来监听这些事件。
完成-
当离线音频上下文的渲染完成时触发。
示例
使用离线音频上下文播放音频
在此示例中,我们声明了 AudioContext 和 OfflineAudioContext 对象。我们使用 AudioContext fetch() 来加载一个音频轨道,然后使用 OfflineAudioContext 将音频渲染到 AudioBufferSourceNode 中并播放该轨道。在设置好离线音频图后,我们使用 OfflineAudioContext.startRendering() 将其渲染到 AudioBuffer。
当 startRendering() 的 Promise 解析时,渲染就已完成,并且输出的 AudioBuffer 会从 Promise 中返回。
此时,我们创建另一个音频上下文,在其内部创建一个 AudioBufferSourceNode,并将其缓冲区设置为等于 Promise 返回的 AudioBuffer。然后,它作为简单标准音频图的一部分进行播放。
// Define both online and offline audio contexts
let audioCtx; // Must be initialized after a user interaction
const offlineCtx = new OfflineAudioContext(2, 44100 * 40, 44100);
// Define constants for dom nodes
const play = document.querySelector("#play");
function getData() {
// Fetch an audio track, decode it and stick it in a buffer.
// Then we put the buffer into the source and can play it.
fetch("viper.ogg")
.then((response) => response.arrayBuffer())
.then((downloadedBuffer) => audioCtx.decodeAudioData(downloadedBuffer))
.then((decodedBuffer) => {
console.log("File downloaded successfully.");
const source = new AudioBufferSourceNode(offlineCtx, {
buffer: decodedBuffer,
});
source.connect(offlineCtx.destination);
return source.start();
})
.then(() => offlineCtx.startRendering())
.then((renderedBuffer) => {
console.log("Rendering completed successfully.");
play.disabled = false;
const song = new AudioBufferSourceNode(audioCtx, {
buffer: renderedBuffer,
});
song.connect(audioCtx.destination);
// Start the song
song.start();
})
.catch((err) => {
console.error(`Error encountered: ${err}`);
});
}
// Activate the play button
play.onclick = () => {
play.disabled = true;
// We can initialize the context as the user clicked.
audioCtx = new AudioContext();
// Fetch the data and start the song
getData();
};
规范
| 规范 |
|---|
| Web Audio API # OfflineAudioContext |
浏览器兼容性
加载中…