【问题标题】:How to fix issue with Web Audio API: DOMException: Unable to decode audio data如何解决 Web Audio API 的问题:DOMException: Unable to decode audio data
【发布时间】:2021-05-16 11:23:00
【问题描述】:

我在尝试使用 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) {
}

【问题讨论】:

    标签: javascript html web audio web-audio-api


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 2016-10-22
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      相关资源
      最近更新 更多