【发布时间】:2015-01-12 11:48:42
【问题描述】:
我正在开发一个 Ionic / Cordova 应用程序,该应用程序涉及从远程服务器加载三分钟的音频剪辑 (mp3) 并播放它们。
我已按照本教程 - http://www.html5rocks.com/en/tutorials/webaudio/intro/ - 并且加载和播放工作正常。
但是我想在本地存储/缓存加载的 mp3,这样用户只需下载一次,应用程序就可以离线工作。这些文件大约为 750 KB。在下面的示例中,文件只有 74 KB。
在应用程序的其他地方,我正在使用 Mozilla 的 localForage(通过 [ngular-localForage),它特别声明它可用于存储 ArrayBuffers - http://mozilla.github.io/localForage/#setitem
但是我似乎无法以我可以播放的格式检索音频...我怀疑我存储了错误的东西 - 我真的不明白 ArrayBuffer 是什么!
无论如何,这是我的基本代码(目前我正在使用本地文件)。 第一次加载音频播放正确,第二次加载出现错误(见下文):
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
function loadDingSound() {
// attempt to retrieve stored file
$localForage.getItem('ding').then(function (response) {
if (response) {
console.log('playing audio from localForage');
console.log(response);
context.decodeAudioData(response, function(buffer) {
playSound(buffer);
});
} else {
var request = new XMLHttpRequest();
request.open('GET', 'audio/ding.mp3', true); // loading local file for now
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
$localForage.setItem('ding', request.response).then(function () {
context.decodeAudioData(request.response, function(buffer) {
playSound(buffer);
});
});
};
request.send();
}
});
}
function playSound(buffer) {
var source = context.createBufferSource(); // creates a sound source
source.buffer = buffer; // tell the source which sound to play
source.connect(context.destination); // connect the source to the context's destination (the speakers)
source.start(0); // play the source now
}
// init
loadDingSound();
我在控制台得到的响应如下:
Object {} // line 13
Error: Failed to execute 'decodeAudioData' on 'AudioContext': invalid ArrayBuffer for audioData. // line 15
目前我只在 Chrome 中进行了测试,而不是 Cordova 应用程序。
我做错了什么?还是有更好的方法来做到这一点?也许我可以将 MP3 保存到文件系统中...?
【问题讨论】:
标签: javascript cordova audio html5-audio localforage