zsoltc
zsoltc

Reputation: 93

Playing audio files with Redux

I'm developing an app in React and Redux. I have a timer thunk which dispatches an action every second and the state is updated to represent the actual time. Now this is great for the UI but I need to play a sound at specific times and I'm not sure where this logic should go.

I could modify the timer thunk to play the sound but this doesn't seem a good solution to me as I think the timer should only be resonsible for dispatching the "time elapsed" actions.

My other idea is to subscribe a listener to the store which will check the state and play the sound when necessary.

Upvotes: 1

Views: 1006

Answers (1)

Yasha
Yasha

Reputation: 1069

How about using a sound store like this:

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]})
  }
}

Then, in your component you can use connect from react-redux to get your state (state.sound.currentSound) and play the sound if there is one. Since the store will be updated every time the action is dispatched, if there is no sound for that time, currentSound will be undefined.

Upvotes: 1

Related Questions