foundation.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. export interface AudioPlayerAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  3. init: () => void;
  4. resetAudioState: () => void;
  5. handleStatusClick: () => void;
  6. handleTimeUpdate: () => void;
  7. handleTrackChange: (direction: 'next' | 'prev') => void;
  8. getAudioRef: () => HTMLAudioElement;
  9. handleTimeChange: (value: number) => void;
  10. handleSpeedChange: (value: { label: string; value: number }) => void;
  11. handleSeek: (direction: number) => void;
  12. handleRefresh: () => void;
  13. handleVolumeChange: (value: number) => void;
  14. destroy: () => void
  15. }
  16. class AudioPlayerFoundation extends BaseFoundation<AudioPlayerAdapter> {
  17. constructor(adapter: AudioPlayerAdapter) {
  18. super({ ...AudioPlayerFoundation, ...adapter });
  19. }
  20. initAudioState() {
  21. const audioElement = this.getAudioRef();
  22. const props = this.getProps();
  23. this.setState({
  24. totalTime: audioElement?.duration || 0,
  25. isPlaying: props.autoPlay,
  26. volume: audioElement?.volume * 100 || 100,
  27. currentRate: { label: '1.0x', value: audioElement?.playbackRate || 1 },
  28. });
  29. }
  30. endHandler() {
  31. const props = this.getProps();
  32. if (Array.isArray(props.audioUrl)) {
  33. this.handleTrackChange('next');
  34. } else {
  35. this.setState({
  36. isPlaying: false,
  37. });
  38. }
  39. }
  40. errorHandler() {
  41. this.setState({
  42. error: true,
  43. });
  44. }
  45. init() {
  46. this._adapter.init();
  47. }
  48. destroy() {
  49. this._adapter.destroy();
  50. }
  51. resetAudioState() {
  52. this._adapter.resetAudioState();
  53. }
  54. handleStatusClick() {
  55. this._adapter.handleStatusClick();
  56. }
  57. handleTimeUpdate() {
  58. this._adapter.handleTimeUpdate();
  59. }
  60. handleTrackChange(direction: 'next' | 'prev') {
  61. this._adapter.handleTrackChange(direction);
  62. }
  63. getAudioRef() {
  64. return this._adapter.getAudioRef();
  65. }
  66. handleTimeChange(value: number) {
  67. this._adapter.handleTimeChange(value);
  68. }
  69. handleSpeedChange(value: { label: string; value: number }) {
  70. this._adapter.handleSpeedChange(value);
  71. }
  72. handleSeek(direction: number) {
  73. this._adapter.handleSeek(direction);
  74. }
  75. handleRefresh() {
  76. this._adapter.handleRefresh();
  77. }
  78. handleVolumeChange(value: number) {
  79. this._adapter.handleVolumeChange(value);
  80. }
  81. }
  82. export default AudioPlayerFoundation;