使用Redux播放音频文件

时间:2016-03-20 14:01:20

标签: javascript reactjs redux

我在React和Redux中开发应用程序。我有一个定时器thunk,每秒调度一次动作,状态更新以代表实际时间。现在这对于用户界面很有用,但我需要在特定时间播放声音,而且我不确定这个逻辑应该去哪里。

我可以修改定时器thunk来播放声音,但这对我来说似乎不是一个好的解决方案,因为我认为定时器应该只适用于调度"时间已过去"动作。

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

1 个答案:

答案 0 :(得分:1)

如何使用这样的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]})
  }
}

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

相关问题