gpt4 book ai didi

ios - 在 Safari 上一次播放多个音频文件

转载 作者:行者123 更新时间:2023-11-29 00:08:46 41 4
gpt4 key购买 nike

我想在 iOS 上同时播放多个音频文件。

单击按钮后,我创建音频文件的多个实例并将它们放入数组中。

let audio = new Audio('path.wav')
audio.play().then(() => {
audio.pause();
possibleAudiosToPlay.push(audio);
});

过了一会儿我把它们全部播放了:

possibleAudiosToPlay.forEach(el => {
el.currentTime = 0;
el.play();
});

虽然这会播放所有音频文件:当新的音频文件开始时,旧的音频文件会停止。 (在 iOS 上)

Apple 开发人员指南表示,这对于 HTML5 音频来说根本不可能:

Playing multiple simultaneous audio streams is also not supported.

但这可以通过 Web Audio API 来实现吗?苹果的开发者指南中没有任何关于它的内容。

最佳答案

是的,您可以使用 Web Audio API .您必须创建一个 AudioBufferSourceNode对于每个音频源,因为每个源只能播放一次(您无法停止并再次播放)。

const AudioContext = window.AudioContext || window.webkitAudioContext;
const ctx = new AudioContext();
const audioPaths = [
"path/to/audio_file1.wav",
"path/to/audio_file2.wav",
"path/to/audio_file3.wav"
];
let promises = [];


// utility function to load an audio file and resolve it as a decoded audio buffer
function getBuffer(url, audioCtx) {
return new Promise((resolve, reject) => {
if (!url) {
reject("Missing url!");
return;
}

if (!audioCtx) {
reject("Missing audio context!");
return;
}

let xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "arraybuffer";

xhr.onload = function() {
let arrayBuffer = xhr.response;
audioCtx.decodeAudioData(arrayBuffer, decodedBuffer => {
resolve(decodedBuffer);
});
};

xhr.onerror = function() {
reject("An error occurred.");
};

xhr.send();
});
}


audioPaths.forEach(p => {
promises.push(getBuffer(p, ctx));
});


// Once all your sounds are loaded, create an AudioBufferSource for each one and start sound
Promise.all(promises).then(buffers => {
buffers.forEach(b => {
let source = ctx.createBufferSource();
source.buffer = b;
source.connect(ctx.destination);
source.start();
})
});

关于ios - 在 Safari 上一次播放多个音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47204048/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com