javascript - 如何解决 Web Audio API 的问题:DOMException: Unable to decode audio data
问题描述
我在尝试使用 Web Audio API 播放音频时遇到问题。我需要能够从服务器返回的字节数组中播放它。如果我将它们保存到文件中并播放它,它会在媒体播放器中播放,但在从 Web 应用程序尝试时不断收到此错误
DOMException:无法解码音频数据
我已经尝试了很多输出格式(wav、ogg、mp3)和比特率,但仍然遇到问题,有什么想法吗?
在最新版本的 Chrome 和 Edge 上测试。
这是我正在使用的代码
var context; // Audio context
var buf; // Audio buffer
export function playAudioBytes(byteArray) {
if (!window.AudioContext) {
if (!window.webkitAudioContext) {
alert("Your browser does not support any AudioContext and cannot play back this audio.");
return;
}
window.AudioContext = window.webkitAudioContext;
}
context = new AudioContext();
playByteArray(byteArray);
}
function playByteArray(bytes) {
var buffer = new Uint8Array(bytes.length);
buffer.set(new Uint8Array(bytes), 0);
context.decodeAudioData(buffer.buffer, play, decodingError);
}
function play(audioBuffer) {
var source = context.createBufferSource();
source.buffer = audioBuffer;
source.connect(context.destination);
source.start(0);
}
function decodingError(error, e1) {
}
解决方案
您还没有提供您的音频文件,但这里有一个来自维基百科的音频文件的工作示例(您可以用自己的替换):
context = new AudioContext();
function play(audioBuffer) {
var source = context.createBufferSource();
source.buffer = audioBuffer;
source.connect(context.destination);
source.start(0);
}
async function fetchAndPlay() {
context.decodeAudioData(
await fetch('https://upload.wikimedia.org/wikipedia/commons/2/28/Karplus-strong-A2.ogg')
.then(r => r.arrayBuffer()),
decoded => play(decoded));
}
fetchAndPlay();
推荐阅读
- google-cloud-firestore - 错误错误:无法加载默认凭据
- jquery - 使用 addEventListener 加载元数据计算视频的总时间并将其保存在全局变量中以在 setinterval 中使用
- xamarin - 如何摆脱 Xamarin.Android 中的两个应用程序图标?
- react-native - 本机模块不能为空
- fullscreen - Uno 平台中非 UWP 应用程序头的全屏模式
- javascript - 为什么我尝试克隆对象没有按预期工作?
- yugabyte-db - 在 YugabyteDB 中,当一个节点发生故障时,故障节点上的 tablet 负载是否均匀分布在其他节点之间?
- python - 命令引发异常:AttributeError: 'Context' object has no attribute 'members'
- node.js - 如何使用 Node.Js 在 MongoDB 中插入或更新数组?
- python - 切片一个nd数组的中间