使用 Redux 播放音频文件

Playing audio files with Redux

本文关键字:文件 音频 播放 Redux 使用      更新时间:2023-09-26

我正在用React和Redux开发一个应用程序。我有一个计时器thunk,它每秒调度一个动作,并且状态更新以表示实际时间。现在这对 UI 来说很棒,但我需要在特定时间播放声音,我不确定这个逻辑应该去哪里。

我可以修改计时器 thunk 来播放声音,但这对我来说似乎不是一个好的解决方案,因为我认为计时器应该只对调度"经过的时间"动作产生共鸣。

我的另一个想法是订阅一个听众到商店,它将检查状态并在必要时播放声音。

像这样使用sound存储怎么样:

const initialState = {
  currentSound: undefined
}
export default function sound(state = initialState, action) {
  switch(action.type) {
    case UPDATE_TIME:
      const time = action.time
      const sounds = {
        6: '/sound1.mp3',
        22: '/sound2.mp3',
        99: '/sound3.mp3'
      }
      return Object.assign({}, state, {currentSound: sounds[time]})
  }
}

然后,在您的组件中,您可以使用 react-redux 中的connect来获取您的状态(state.sound.currentSound)并播放声音(如果有)。由于每次调度操作时都会更新商店,因此如果当时没有声音,则将currentSound undefined