android - ReactNative & Expo - 错误:“值”是只读的
问题描述
我正在向这个反应原生应用程序添加一个音乐播放器组件/功能。我将包含所有相关代码,以便您更好地了解设置。
在处理音乐播放器逻辑的上下文文件 MusicContext.js 中,我有几个 State 对象用于确定播放哪首歌。
const initialState = {
startMusic: () => null,
stopMusic: () => null,
soundObject: null,
isPlaying: false,
currentIndex: 0
}
我的歌曲数组:
mainTheme = new Audio.Sound()
mainTheme2 = new Audio.Sound()
mainTheme3 = new Audio.Sound()
const songs = [
{ path: require("../assets/sounds/MainTheme.mp3"), song: mainTheme },
{ path: require("../assets/sounds/MainTheme2.mp3"), song: mainTheme2 },
{ path: require("../assets/sounds/MainTheme3.mp3"), song: mainTheme3 },
]
currentIndex 从 0 开始,因此音乐播放器将从歌曲 [0] 开始。
开始播放音乐的函数如下:
const startMusic = async () => {
try {
const songToPlay = songs[currentIndex].song // first song in the array of songs
const source = songs[currentIndex].path // the path that loadAsync() function needs to load file
await songToPlay.loadAsync(source)
await songToPlay.playAsync()
setSoundObject(songToPlay)
setIsPlaying(true)
return new Promise(resolve => {
songToPlay.setOnPlaybackStatusUpdate(playbackStatus => {
if (playbackStatus.didJustFinish) {
console.log("Song finished")
resolve()
}
})
})
} catch (error) {
console.log(`Error: ${error}`)
return
}
}
此时,soundObject = 正在播放的歌曲,currentIndex = 0。我跳到下一首歌的函数是:
const handleNextTrack = async () => {
if (soundObject) {
await soundObject.stopAsync()
await soundObject.unloadAsync()
setSoundObject(null)
currentIndex < songs.length - 1 ? (currentIndex += 1) : (currentIndex = 0)
setCurrentIndex({ currentIndex })
this.startMusic()
}
}
之后,它回到startMusic()
,除了现在 currentIndex 为 1,它应该播放数组中的下一首歌曲。
我得到的错误是
Possible Unhandled Promise Rejection (id: 5): Error: "currentIndex" is read-only
我尝试了几种不同的实现方式,handleNextTrack
但都导致了同样的错误。
更新
const handlePreviousTrack = async () => {
if (soundObject) {
await soundObject.stopAsync()
await soundObject.unloadAsync()
setSoundObject(null)
let newIndex = currentIndex
newIndex < (songs.length - 1) ? (--newIndex) : (newIndex = 0)
setCurrentIndex(newIndex)
startMusic()
}
}
const handleNextTrack = async () => {
if (soundObject) {
await soundObject.stopAsync()
await soundObject.unloadAsync()
setSoundObject(null)
let newIndex = currentIndex
newIndex < (songs.length - 1) ? (++newIndex) : (newIndex = 0)
setCurrentIndex(newIndex)
startMusic()
}
}
歌曲[0] 在应用打开时播放。<~好
next
当我点击<~BAD时,歌曲 [0] 再次播放
Song[1] 只有在我next
第二次击球时才会播放 <~GOOD
如果我再次击球,就会播放歌曲 [2] next
<~GOOD
之后,我可以循环一点,击打previous
几次next
,但它刚刚坏了,并且声音对象不知何故又回到了null
解决方案
推荐阅读
- sql - 如何使用 LINQ 包含在 SQL 中
- .net-core - 使用 B2C 生成元数据端点时,id_token_hint 参数签名验证失败
- javascript - 如何使用 vanilla JS 从重绘中删除画布
- typescript - 为什么在 Typescript 中访问缺少的 getter 会返回“未定义”而不是导致编译错误?
- r - 基于R中的两个嵌套条件过滤数据帧的最有效算法?
- postgresql - 如何确保两个引用的外键表对另一个表具有相同的外键?
- azure - 基于身份的身份验证不适用于 Azure 存储文件共享
- google-sheets - 如何在Google电子表格中检查多张表格中的数据,但排除一张
- sql - 调试导致“资源超出”错误的行
- javascript - 反应 ScrollableTabView onChangeTab