【发布时间】:2018-07-01 09:34:09
【问题描述】:
我正在学习 WebAudio API。我面临一个问题。基本上这里的事情是异步的......所以我有点困惑。请帮忙。这是我的代码:-
//"use strict";
var sources = new Array();
var actx;
var songs = ['src1.mp3', 'src2.mp3'];
async function start() {
console.log("WELCOME!!");
try {
actx = new AudioContext();
} catch (e) {
console.log('WebAudio api is not supported!!');
}
await getBuffers(actx, songs);
console.log(sources);
console.log(sources.length);
}
function load_song(url) {
let promise = new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = () => {
let audioData = request.response;
resolve(audioData);
}
request.onerror = () => {
reject(new error("Could not load the song:- " + url));
}
request.send();
});
return promise;
}
//creats buffers
async function getBuffers(actx, songs) {
// let buffer_list = new Array();
for (let x = 0; x < songs.length; x++) {
let temp = actx.createBufferSource();
await load_song(songs[x]).then((audioData) => {
actx.decodeAudioData(audioData).then((decodedAudioData) => {
temp.buffer = decodedAudioData;
sources.push(temp);
}).catch((error) => {
console.error(error);
});
});
}
//console.log(buffers.length);
}
async function play() {
//start();
sources[0].start(0);
//sources[1].start(0);
}
function stop() {
sources[0].stop(0);
//sources[1].stop(0);
}
在console.log(sources) 和console.log(sources.length) 两行中。结果在这里。为什么console.log(sources.length) 为 0?
请帮帮我........谢谢。
【问题讨论】:
-
console.log(sources)由于 chrome 的行为,当您在开发者控制台中展开它时会评估它,此时数组已被填充,但是当您记录长度时,数组尚未填充。 -
await load_song(songs[x]).then你的混合async/await与 thenable 回调.. 尝试const audioData = await load_song(songs[x])
标签: javascript arrays async-await es6-promise web-audio-api