index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  2. import React from 'react';
  3. import cls from 'classnames';
  4. import '@douyinfe/semi-foundation/audioPlayer/audioPlayer.scss';
  5. import { cssClasses } from '@douyinfe/semi-foundation/audioPlayer/constants';
  6. import Button from '../button';
  7. import Dropdown from '../dropdown';
  8. import Image from '../image';
  9. import Tooltip from '../tooltip';
  10. import Popover from '../popover';
  11. import { IconAlertCircle, IconBackward, IconFastForward, IconPause, IconPlay, IconRefresh, IconRestart, IconVolume2, IconVolumnSilent } from '@douyinfe/semi-icons';
  12. import AudioSlider from './audioSlider';
  13. import AudioPlayerFoundation from '@douyinfe/semi-foundation/audioPlayer/foundation';
  14. import { AudioPlayerAdapter } from '@douyinfe/semi-foundation/audioPlayer/foundation';
  15. import { formatTime } from './utils';
  16. type AudioSrc = string
  17. type AudioInfo = {
  18. title?: string;
  19. cover?: string;
  20. src: string
  21. }
  22. type AudioUrlArray = (AudioInfo | string)[];
  23. type AudioUrl = AudioSrc | AudioInfo | AudioUrlArray
  24. export type AudioPlayerTheme = 'dark' | 'light'
  25. export interface AudioPlayerProps extends BaseProps {
  26. audioUrl: AudioUrl;
  27. autoPlay: boolean;
  28. showToolbar?: boolean;
  29. skipDuration?: number;
  30. theme?: AudioPlayerTheme;
  31. className?: string;
  32. style?: React.CSSProperties
  33. }
  34. export interface AudioPlayerState {
  35. isPlaying: boolean;
  36. currentIndex: number;
  37. totalTime: number;
  38. currentTime: number;
  39. currentRate: { label: string; value: number };
  40. volume: number;
  41. error: boolean
  42. }
  43. const prefixCls = cssClasses.PREFIX;
  44. class AudioPlayer extends BaseComponent<AudioPlayerProps, AudioPlayerState> {
  45. audioRef = React.createRef<HTMLAudioElement>();
  46. static defaultProps: Partial<AudioPlayerProps> = {
  47. autoPlay: false,
  48. showToolbar: true,
  49. skipDuration: 10,
  50. theme: 'dark',
  51. };
  52. rateOptions = [
  53. { label: '0.5x', value: 0.5 },
  54. { label: '0.75x', value: 0.75 },
  55. { label: '1.0x', value: 1 },
  56. { label: '1.5x', value: 1.5 },
  57. { label: '2.0x', value: 2 },
  58. ];
  59. foundation!: AudioPlayerFoundation;
  60. constructor(props: AudioPlayerProps) {
  61. super(props);
  62. this.state = {
  63. isPlaying: false,
  64. currentIndex: 0,
  65. totalTime: 0,
  66. currentTime: 0,
  67. currentRate: { label: '1.0x', value: 1 },
  68. volume: 100,
  69. error: false,
  70. };
  71. this.audioRef = React.createRef<HTMLAudioElement>();
  72. this.foundation = new AudioPlayerFoundation(this.adapter);
  73. }
  74. get adapter(): AudioPlayerAdapter<AudioPlayerProps, AudioPlayerState> {
  75. return {
  76. ...super.adapter,
  77. init: () => {
  78. if (this.audioRef.current) {
  79. this.audioRef.current.addEventListener('loadedmetadata', () => {
  80. this.foundation.initAudioState();
  81. });
  82. this.audioRef.current.addEventListener('error', () => {
  83. this.foundation.errorHandler();
  84. });
  85. this.audioRef.current.addEventListener('ended', () => {
  86. this.foundation.endHandler();
  87. });
  88. }
  89. },
  90. destroy: () => {
  91. if (this.audioRef.current) {
  92. this.audioRef.current.removeEventListener('loadedmetadata', () => {
  93. this.foundation.initAudioState();
  94. });
  95. this.audioRef.current.removeEventListener('error', () => {
  96. this.foundation.errorHandler();
  97. });
  98. this.audioRef.current.removeEventListener('ended', () => {
  99. this.foundation.endHandler();
  100. });
  101. }
  102. },
  103. handleStatusClick: () => {
  104. if (!this.audioRef.current) return;
  105. if (this.state.isPlaying) {
  106. this.audioRef.current.pause();
  107. } else {
  108. this.audioRef.current.play();
  109. }
  110. this.setState({
  111. isPlaying: !this.state.isPlaying,
  112. });
  113. },
  114. getAudioRef: () => this.audioRef.current,
  115. resetAudioState: () => {
  116. this.setState({
  117. isPlaying: true,
  118. currentTime: 0,
  119. currentRate: { label: '1.0x', value: 1 }
  120. }, () => {
  121. if (this.audioRef.current) {
  122. this.audioRef.current.currentTime = this.state.currentTime;
  123. this.audioRef.current.playbackRate = this.state.currentRate.value;
  124. this.audioRef.current.play();
  125. }
  126. });
  127. },
  128. handleTimeUpdate: () => {
  129. if (!this.audioRef.current) return;
  130. this.setState({
  131. currentTime: this.audioRef.current.currentTime,
  132. });
  133. },
  134. handleTrackChange: (direction: 'next' | 'prev') => {
  135. if (!this.audioRef.current) return;
  136. const { audioUrl } = this.props as AudioPlayerProps;
  137. const isAudioUrlArray = Array.isArray(audioUrl);
  138. if (isAudioUrlArray) {
  139. if (direction === 'next') {
  140. this.setState({
  141. currentIndex: (this.state.currentIndex + 1) % audioUrl.length,
  142. error: false,
  143. });
  144. } else {
  145. this.setState({
  146. currentIndex: (this.state.currentIndex - 1 + audioUrl.length) % audioUrl.length,
  147. error: false,
  148. });
  149. }
  150. }
  151. this.foundation.resetAudioState();
  152. },
  153. handleTimeChange: (value: number) => {
  154. if (!this.audioRef.current) return;
  155. this.audioRef.current.currentTime = value;
  156. this.setState({
  157. currentTime: value,
  158. });
  159. },
  160. handleRefresh: () => {
  161. if (!this.audioRef.current) return;
  162. if (this.state.error) {
  163. this.audioRef.current.load();
  164. } else {
  165. this.audioRef.current.currentTime = 0;
  166. this.setState({
  167. currentTime: 0,
  168. });
  169. }
  170. },
  171. handleSpeedChange: (value: { label: string; value: number }) => {
  172. if (!this.audioRef.current) return;
  173. this.audioRef.current.playbackRate = value.value;
  174. this.setState({
  175. currentRate: value,
  176. });
  177. },
  178. handleSeek: (direction: number) => {
  179. if (!this.audioRef.current) return;
  180. const { skipDuration = 10 } = this.props;
  181. const newTime = Math.min(
  182. Math.max(this.audioRef.current.currentTime + (direction * skipDuration), 0),
  183. this.audioRef.current.duration
  184. );
  185. this.audioRef.current.currentTime = newTime;
  186. },
  187. handleVolumeChange: (value: number) => {
  188. if (!this.audioRef.current) return;
  189. const volume = Math.floor(value);
  190. this.audioRef.current.volume = volume / 100;
  191. this.setState({
  192. volume: volume,
  193. });
  194. },
  195. };
  196. }
  197. componentDidMount() {
  198. this.foundation.init();
  199. }
  200. componentWillUnmount() {
  201. this.foundation.destroy();
  202. }
  203. handleStatusClick = () => {
  204. this.foundation.handleStatusClick();
  205. }
  206. handleTrackChange = (direction: 'next' | 'prev') => {
  207. this.foundation.handleTrackChange(direction);
  208. }
  209. handleTimeChange = (value: number) => {
  210. this.foundation.handleTimeChange(value);
  211. }
  212. handleRefresh = () => {
  213. this.foundation.handleRefresh();
  214. }
  215. handleSpeedChange = (value: { label: string; value: number }) => {
  216. this.foundation.handleSpeedChange(value);
  217. }
  218. handleSeek = (direction: number) => {
  219. this.foundation.handleSeek(direction);
  220. }
  221. handleTimeUpdate = () => {
  222. this.foundation.handleTimeUpdate();
  223. }
  224. handleVolumeChange = (value: number) => {
  225. this.foundation.handleVolumeChange(value);
  226. }
  227. handleVolumeSilent = () => {
  228. if (!this.audioRef.current) return;
  229. this.audioRef.current.volume = this.state.volume === 0 ? 0.5 : 0;
  230. this.setState({
  231. volume: this.state.volume === 0 ? 50 : 0,
  232. });
  233. }
  234. getAudioInfo = (audioUrl: AudioUrl) => {
  235. const isAudioUrlArray = Array.isArray(audioUrl);
  236. if (isAudioUrlArray) {
  237. const audioInfo = audioUrl[this.state.currentIndex];
  238. if (typeof audioInfo === 'string') {
  239. return { src: audioInfo, audioTitle: null, audioCover: null };
  240. } else {
  241. return { src: audioInfo.src, audioTitle: audioInfo.title, audioCover: audioInfo.cover };
  242. }
  243. } else if (typeof audioUrl === 'string') {
  244. return { src: audioUrl, audioTitle: null, audioCover: null };
  245. } else {
  246. return { src: audioUrl.src, audioTitle: audioUrl.title, audioCover: audioUrl.cover };
  247. }
  248. }
  249. renderControl = () => {
  250. const { error } = this.state;
  251. const isAudioUrlArray = Array.isArray(this.props.audioUrl);
  252. const iconClass = cls(`${prefixCls}-control-button-icon`);
  253. const circleStyle = {
  254. borderRadius: '50%',
  255. };
  256. const transparentStyle = {
  257. background: 'transparent',
  258. };
  259. const playStyle = {
  260. marginLeft: '1px',
  261. };
  262. return <div className={cls(`${prefixCls}-control`)}>
  263. {isAudioUrlArray && <Tooltip content='Previous' autoAdjustOverflow showArrow={false}>
  264. <Button style={{ ...circleStyle, ...transparentStyle }} size='large' icon={<IconRestart size='large' className={iconClass} />} onClick={() => this.handleTrackChange('prev')} />
  265. </Tooltip>}
  266. <Button style={circleStyle} size='large' disabled={error} onClick={this.handleStatusClick} icon={this.state.isPlaying ? <IconPause size='large' /> : <IconPlay style={playStyle} size='large' />} className={cls(`${cssClasses.PREFIX}-control-button-play`, { [`${cssClasses.PREFIX}-control-button-play-disabled`]: error })} />
  267. {isAudioUrlArray && <Tooltip content='Next' autoAdjustOverflow showArrow={false}>
  268. <Button style={{ ...circleStyle, ...transparentStyle }} size='large' icon={<IconRestart size='large' rotate={180} className={iconClass} />} onClick={() => this.handleTrackChange('next')} />
  269. </Tooltip>}
  270. </div>;
  271. }
  272. renderInfo = () => {
  273. const { audioTitle, audioCover } = this.getAudioInfo(this.props.audioUrl);
  274. const { theme } = this.props;
  275. const { currentTime, totalTime, error } = this.state;
  276. return <div className={cls(`${prefixCls}-info-container`)}>
  277. {audioCover && <Image src={audioCover} width={50} height={50} />}
  278. <div className={cls(`${prefixCls}-info`)}>
  279. {audioTitle && <div className={cls(`${prefixCls}-info-title`)}>{audioTitle}{error && this.renderError()}</div>}
  280. {!error && <div className={cls(`${prefixCls}-info-time`)}>
  281. <span style={{ width: '38px' }}>{formatTime(currentTime)}</span>
  282. <div className={cls(`${prefixCls}-slider-container`)}>
  283. <AudioSlider value={currentTime} max={totalTime} theme={theme} onChange={this.handleTimeChange} />
  284. </div>
  285. <span style={{ width: '38px' }}>{formatTime(totalTime)}</span>
  286. </div>}
  287. </div>
  288. </div>;
  289. }
  290. renderToolbar = () => {
  291. const { volume, error } = this.state;
  292. const { skipDuration = 10, theme = 'dark' } = this.props;
  293. const iconClass = cls(`${prefixCls}-control-button-icon`);
  294. const transparentStyle = {
  295. background: 'transparent',
  296. };
  297. const isVolumeSilent = volume === 0;
  298. return !error ? (<div className={cls(`${prefixCls}-control`)}>
  299. <Popover autoAdjustOverflow content={
  300. <div className={cls(`${prefixCls}-control-volume`)}>
  301. <div className={cls(`${prefixCls}-control-volume-title`)}>{volume}%</div>
  302. <AudioSlider value={volume} max={100} vertical height={120} theme={theme} showTooltip={false} onChange={this.handleVolumeChange} />
  303. </div>
  304. }>
  305. <Button style={transparentStyle} icon={!isVolumeSilent ? <IconVolume2 className={iconClass} /> : <IconVolumnSilent className={iconClass} />} onClick={this.handleVolumeSilent} />
  306. </Popover>
  307. <Tooltip content={`Backward ${skipDuration}s`} autoAdjustOverflow showArrow={false}>
  308. <Button
  309. style={transparentStyle}
  310. icon={<IconBackward className={iconClass} />}
  311. onClick={() => this.handleSeek(-1)}
  312. />
  313. </Tooltip>
  314. <Tooltip content={`Forward ${skipDuration}s`} autoAdjustOverflow showArrow={false}>
  315. <Button
  316. style={transparentStyle}
  317. icon={<IconFastForward className={iconClass} />}
  318. onClick={() => this.handleSeek(1)}
  319. />
  320. </Tooltip>
  321. <Dropdown className={cls(`${prefixCls}-control-speed-menu`)} render={<Dropdown.Menu>
  322. {this.rateOptions.map((option) => (
  323. <Dropdown.Item className={cls(`${prefixCls}-control-speed-menu-item`)} key={option.value} onClick={() => this.handleSpeedChange(option)} active={option.value === this.state.currentRate.value}>
  324. {option.label}
  325. </Dropdown.Item>
  326. ))}
  327. </Dropdown.Menu>} onChange={this.handleSpeedChange}>
  328. <div className={cls(`${prefixCls}-control-speed`)}>
  329. <span>{this.state.currentRate.label}</span>
  330. </div>
  331. </Dropdown>
  332. <Button onClick={() => this.handleRefresh()} style={transparentStyle} icon={<IconRefresh style={{ transform: 'rotateY(180deg)' }} className={iconClass} />} />
  333. </div>) : (<div className={cls(`${prefixCls}-control`)}>
  334. <Button onClick={() => this.handleRefresh()} style={transparentStyle} icon={<IconRefresh style={{ transform: 'rotateY(180deg)' }} className={iconClass} />} />
  335. </div>);
  336. }
  337. renderError = () => <div className={cls(`${prefixCls}-error`)}><IconAlertCircle size='large' />音频加载失败</div>
  338. render() {
  339. const { audioUrl, autoPlay, className, style, showToolbar = true, theme = 'dark' } = this.props as AudioPlayerProps;
  340. const src = this.getAudioInfo(audioUrl).src;
  341. return (
  342. <div className={cls(prefixCls, className, `${prefixCls}-${theme}`)} style={style}>
  343. <audio src={src} autoPlay={autoPlay} className={cls(prefixCls, className)} style={style} ref={this.audioRef} onTimeUpdate={this.handleTimeUpdate}>
  344. <track kind="captions" src={src} />
  345. </audio>
  346. {this.renderControl()}
  347. {this.renderInfo()}
  348. {showToolbar && this.renderToolbar()}
  349. </div>
  350. );
  351. }
  352. }
  353. export default AudioPlayer;