我的游戏有背景音乐和单独的声音,我以不同的方式播放它们。问题是循环播放的背景音乐在某个时刻会消失,一些声音播放时会出现缺陷。以下是一些...
我的游戏有背景音乐和单独的声音,我以不同的方式播放它们。问题是循环播放的背景音乐在某个时刻会消失,一些声音播放有缺陷。
以下是执行这些功能的 JS 代码
const allSounds = []
let allSoundsName = [
//names of sounds
]
function preloadSounds() {
allSoundsName.forEach(soundName => {
let audio = new Audio(`./assets/audio/${soundName}.mp3`)
allSounds.push({
name: soundName,
audio: audio,
})
})
}
function playAudio({
audioName,
isLoop,
startTime = 0,
endTime = null,
volume = 1,
delay = 0,
decrease = 0,
duration,
}) {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
audioCtx.onstatechange = () => {
if (audioCtx.state === 'suspended') {
console.log('suspended')
audioCtx.resume();
}
};
addAllSoundGain()
}
let sound = getSound(audioName)
setVolume(sound, off ? 0 : volume)
if (volume !== 1) addVolumes(audioName, volume)
sound.audio.currentTime = startTime
if (endTime) {
setTime(sound.audio, startTime, endTime, isLoop)
} else if (isLoop) {
setLoop(sound.audio, startTime)
}
setTimeout(() => {
sound.audio.play()
setDurationAndDecrease(sound.audio, audioName, duration, decrease)
}, delay)
return sound.audio
}
function addAllSoundGain() {
allSounds.forEach(sound => {
let source = audioCtx.createMediaElementSource(sound.audio);
let gainNode = audioCtx.createGain();
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
sound.source = source
sound.gainNode = gainNode
})
}
function setDurationAndDecrease(audio, audioName, duration, decrease) {
if (duration) setTimeout(() => pauseAudio({audioName, decrease}), duration)
}
function setLoop(audio, startTime) {
audio.onended = () => {
audio.currentTime = startTime
audio.play()
}
}
function setTime(audio, startTime, endTime, isLoop) {
audio.ontimeupdate = () => {
if (audio.currentTime >= endTime && isLoop) {
audio.currentTime = startTime
} else if (audio.currentTime >= endTime) {
audio.pause()
}
}
}
我不知道该怎么办,因为 Chrome 中一切都很好,这个问题只发生在 Safari Mac 中