尝试在Google Chrome中加载mp3音频文件时出现以下错误:Uncaught (in promise) DOMException: Unable to decode audio data
。这是我的代码:
loadSong(url) {
var AudioCtx = new AudioContext();
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = "arraybuffer";
request.onload = function () {
console.log(request.response);
AudioCtx.decodeAudioData(
request.response,
function (buffer) {
var currentSong = AudioCtx.createBufferSource();
currentSong.buffer = buffer;
currentSong.connect(AudioCtx.destination);
currentSong.start(0);
},
function (e) {
alert("error: " + e.err);
}
);
};
request.send();
}
这是request.response
的console.log:
ArrayBuffer(153) {}
byteLength:0
__proto__:ArrayBuffer
byteLength:0
constructor:ƒ ArrayBuffer()
slice:ƒ slice()
Symbol(Symbol.toStringTag):"ArrayBuffer"
get byteLength:ƒ byteLength()
__proto__:Object
在Firefox中我收到错误The buffer passed to decodeAudioData contains an unknown type of content.
。与OGG文件相同的错误
答案 0 :(得分:-1)
为什么首先要让它变得如此复杂:P?
使用外部脚本处理SoundPlayer.js等音频。它基于Web Audio API,不接触DOM。
加载SoundPlayer.js脚本:
<script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/SoundPlayer.js"></script>
只需使用:
const player = new SoundPlayer();
player.load( 'file.mp3' ).play();
或阅读README.md
无论如何,由于文件丢失或者有其他名称以及不支持文件类型,代码中可能会出现Unable to decode audio data
错误。