这是我第一次与expo 合作,我学到了很多东西,但这仍然是我无法解决的问题.
我正在使用expo-av,对于简短的声音,我没有任何问题.他们踢球,然后我拨打unloadAsync()
,那里没有问题.但说到背景音乐,我会停下来,卸载,确保useEffect正在恢复,但由于某种原因,即使在游戏结束后,我被送到游戏结束或胜利屏幕后,音乐仍在继续播放,如果出于某种原因,我试图开始另一场游戏,它将是一个音频叠加在另一个之上.
在负责设置回放的类内部:
class AudioController {
constructor() {
this.bgMusic = new Audio.Sound()
this.flipSound = new Audio.Sound()
this.matchSound = new Audio.Sound()
this.victorySound = new Audio.Sound()
this.gameOverSound = new Audio.Sound()
}
loadAndPlay = async (audioObject, audioFile, loop = false, volume = 1.0) => {
try {
await audioObject.loadAsync(audioFile);
audioObject.setIsLoopingAsync(loop);
audioObject.setVolumeAsync(volume);
await audioObject
.playAsync()
.then(async playbackStatus => {
if (!loop) {
setTimeout(() => {
audioObject.unloadAsync()
}, playbackStatus.playableDurationMillis)
}
})
.catch(error => {
console.log(error)
})
} catch (error) {
console.log(error);
}
}
playBgMusic = async () => {
await this.loadAndPlay(this.bgMusic, bgMusic, true, 0.5); // Loop and set the volume to 50%
}
stopBgMusic = async () => {
try {
await this.bgMusic.stopAsync();
await this.bgMusic.unloadAsync();
} catch (error) {
console.log(error);
}
}
playFlipSound = async () => {
await this.loadAndPlay(this.flipSound, flipSound);
}
playMatchSound = async () => {
await this.loadAndPlay(this.matchSound, matchSound);
}
playVictorySound = async () => {
await this.loadAndPlay(this.victorySound, victorySound);
}
playGameOverSound = async () => {
await this.loadAndPlay(this.gameOverSound, gameOverSound);
}
}
export default AudioController``
Inside the component where I want to use it.
`useEffect(() => {
audioController.playBgMusic()
resetTurn()
setTimer(level)
shuffleCards()
return () => {
console.log(' Start game cleanup executed')
audioController.stopBgMusic()
}
}, []);`
当然,我正确地实例化了音频控制器(否则其他声音将不起作用),并且我正在触发游戏结束和胜利功能.所以问题要么是我试图停止音乐的方式,要么是组件没有卸载.我也试着在它把我送到一个不同的屏幕之前,停止处理游戏的功能中的音乐,但仍然是一样的.我也try 了使用Reaction上下文,结果是一样的,如果我try 开始一个新游戏,音乐不会停止,新的实例将会启动.