PlayerReducer.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import React, {createContext, useReducer} from 'react';
  2. const PlayerStateContext = createContext();
  3. const PlayerDispatchContext = createContext();
  4. const initialPlayerState = {
  5. volume: 1,
  6. muted: false,
  7. duration: 0.0,
  8. currentTime: 0.0,
  9. currentPosition: 0.0,
  10. paused: true,
  11. uri: 'https://sample-videos.com/audio/mp3/crowd-cheering.mp3',
  12. player: null
  13. };
  14. const playerReducer = (state, action) => {
  15. switch(action.type) {
  16. case 'muted':
  17. return {
  18. ...state,
  19. muted: !state.muted
  20. };
  21. case 'paused':
  22. return {
  23. ...state,
  24. paused: action.setPaused
  25. };
  26. case 'uri':
  27. return {
  28. ...state,
  29. uri: action.setUri
  30. };
  31. case 'duration':
  32. return {
  33. ...state,
  34. duration: action.setDuraton
  35. };
  36. case 'currentTime':
  37. return {
  38. ...state,
  39. currentTime: action.setCurrentTime
  40. };
  41. case 'currentPosition':
  42. return {
  43. ...state,
  44. currentPosition: action.setCurrentPosition
  45. };
  46. case 'player':
  47. return {
  48. ...state,
  49. player: action.player
  50. };
  51. case 'seek':
  52. state.player && state.player.current.seek(action.seekValue);
  53. return state;
  54. case 'stop':
  55. state.player && state.player.current.seek(0);
  56. return state;
  57. default: throw new Error('Action type is not match');
  58. }
  59. };
  60. const PlayerConextProvider = ({children}) => {
  61. const [playerState, playerDispatch] = useReducer(playerReducer, initialPlayerState);
  62. return (
  63. <PlayerDispatchContext.Provider value={playerDispatch}>
  64. <PlayerStateContext.Provider value={playerState}>
  65. {children}
  66. </PlayerStateContext.Provider>
  67. </PlayerDispatchContext.Provider>
  68. );
  69. }
  70. /**
  71. * Player Common Function
  72. */
  73. const secondsTohhmmss = (seconds, timeFormat='hmmss') => {
  74. const format = val => `0${Math.floor(val)}`.slice(-2);
  75. const hours = seconds / 3600;
  76. const minutes = (seconds % 3600) / 60;
  77. if(timeFormat==='mmss' || ~~hours===0) {
  78. return [minutes, seconds % 60].map(format).join(':');
  79. }
  80. if(timeFormat==='hmmss') {
  81. return `${~~hours}:${[minutes, seconds % 60].map(format).join(':')}`;
  82. }
  83. if(timeFormat==='hhmmss') {
  84. return [hours, minutes, seconds % 60].map(format).join(':');
  85. }
  86. }
  87. const playerCommon = {
  88. secondsTohhmmss: secondsTohhmmss
  89. };
  90. export { PlayerDispatchContext, PlayerStateContext, PlayerConextProvider, playerCommon }