首页 > 解决方案 > 如何解决 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) {
}

标签: javascripthtmlwebaudioweb-audio-api

解决方案


您还没有提供您的音频文件,但这里有一个来自维基百科的音频文件的工作示例(您可以用自己的替换):

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();

推荐阅读