使用声音文件的expo-av库为React Native应用分配作业。现在,该应用程序在上下文文件中设置了startMusic
功能,该功能负责播放应用程序的背景音乐。目前只有一首歌:
const startMusic = async () => {
try {
await mainTheme.loadAsync(require("../assets/sounds/Katsu.mp3"))
await mainTheme.playAsync()
setSoundObject(mainTheme)
console.log("The first song is playing! Enjoy!")
} catch (error) {
console.log(`Couldnt load main theme: ${error}`)
return
}
}
像这样在主屏幕组件的文件中使用:
const { startMusic } = useContext(MusicContext)
useEffect(() => {
startMusic()
}, [])
[第二首歌,我在MusicContext文件中写了另一个const:
const secondSong = async () => {
try {
await mainTheme2.loadAsync(require("../assets/sounds/MainTheme2.mp3"))
await mainTheme2.playAsync()
setSoundObject(mainTheme2)
console.log("Now playing the second track. Enjoy!")
} catch (error) {
console.log(`Could not play the second song: ${error}`)
return
}
}
Annnnnd…这就是我的麻烦所在。我知道这是行不通的,但我在组件文件中编写了此文件,以尝试使第二首歌播放在第一首歌之后]
useEffect(() => { startMusic() .then(secondSong()) }, [])
我知道还有很多,但是我遇到了麻烦。
使用声音文件的expo-av库为React Native应用分配作业。现在,该应用程序在上下文文件中设置了一个startMusic函数,该函数负责播放该应用程序的...
您的代码问题不仅是一个函数接一个运行(这很简单,就像startMusic().then(() => secondSong())
一样,但仍然无法解决问题),而是您的函数实际上不等待歌曲完成的事实解决之前播放
我认为您需要重新考虑此问题/解决方案以更抽象。
.then()
接受一个函数,但是您已经通过调用secondSong
提供了函数执行的结果。