我需要加载一个mp3,切片并使用网络音频播放它,在firefox上切片mp3任何地方和解码工作正常,但在safari上出现一个带有空值的错误。存在一个技巧或方法在Safari上切片ArrayBuffer?
player.loadMp3 = function(url, callback) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
var mp3slice = request.response.slice(1000,100000);
player.context.decodeAudioData(mp3slice); // context is webkitAudioContext on safari
callback();
};
request.send();
};
我需要创建一个具有一些特殊功能的mp3播放器:
解决方案
player.loadMp3 = function(url, callback) {
console.log("loading " + url);
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
console.log("loaded");
console.log("decoding...");
player.context.decodeAudioData(request.response, function(buffer) {
console.log("decoded");
player.buffer = player.joinAudioBuffers(player.buffer,buffer,2000000);
player.duration += player.buffer.duration;
player.time = minsSecs(player.buffer.duration);
console.log("concatenated");
callback();
});
}, function() {
alert("decode failure");
};
request.send();
};
答案 0 :(得分:1)
您展示的代码不适用于任何浏览器。首先,您需要为decodeAudioData提供回调函数。您还需要在解码之后对解码的数据进行切片,而不是在解码之前对原始mp3编码数据进行切片。有些浏览器可能能够解码一段mp3文件,但这并不是预期的。像这样:
player.loadMp3 = function(url, callback) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
var mp3slice = request.response.slice(1000,100000);
player.context.decodeAudioData(mp3slice, function(decoded) {
var pcmSlice = decoded.slice(1000, 100000);
callback(pcmSlice);
});
};
request.send();
};
我还没有测试过这段代码。