您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

AudioTrack.tsx 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import React, { Component } from 'react';
  2. import { connect } from 'react-redux';
  3. import { createAudioPlayErrorEvent, createAudioPlaySuccessEvent } from '../../../../analytics/AnalyticsEvents';
  4. import { sendAnalytics } from '../../../../analytics/functions';
  5. import { IReduxState } from '../../../../app/types';
  6. import { ITrack } from '../../../tracks/types';
  7. import logger from '../../logger';
  8. /**
  9. * The type of the React {@code Component} props of {@link AudioTrack}.
  10. */
  11. interface IProps {
  12. /**
  13. * Represents muted property of the underlying audio element.
  14. */
  15. _muted?: boolean;
  16. /**
  17. * Represents volume property of the underlying audio element.
  18. */
  19. _volume?: number | boolean;
  20. /**
  21. * The audio track.
  22. */
  23. audioTrack?: ITrack;
  24. /**
  25. * Used to determine the value of the autoplay attribute of the underlying
  26. * audio element.
  27. */
  28. autoPlay: boolean;
  29. /**
  30. * The value of the id attribute of the audio element.
  31. */
  32. id: string;
  33. /**
  34. * The ID of the participant associated with the audio element.
  35. */
  36. participantId: string;
  37. }
  38. /**
  39. * The React/Web {@link Component} which is similar to and wraps around {@code HTMLAudioElement}.
  40. */
  41. class AudioTrack extends Component<IProps> {
  42. /**
  43. * Reference to the HTML audio element, stored until the file is ready.
  44. */
  45. _ref: HTMLAudioElement | null;
  46. /**
  47. * The current timeout ID for play() retries.
  48. */
  49. _playTimeout: number | undefined;
  50. /**
  51. * Default values for {@code AudioTrack} component's properties.
  52. *
  53. * @static
  54. */
  55. static defaultProps = {
  56. autoPlay: true,
  57. id: ''
  58. };
  59. /**
  60. * Creates new <code>Audio</code> element instance with given props.
  61. *
  62. * @param {Object} props - The read-only properties with which the new
  63. * instance is to be initialized.
  64. */
  65. constructor(props: IProps) {
  66. super(props);
  67. // Bind event handlers so they are only bound once for every instance.
  68. this._errorHandler = this._errorHandler.bind(this);
  69. this._setRef = this._setRef.bind(this);
  70. this._play = this._play.bind(this);
  71. }
  72. /**
  73. * Attaches the audio track to the audio element and plays it.
  74. *
  75. * @inheritdoc
  76. * @returns {void}
  77. */
  78. componentDidMount() {
  79. this._attachTrack(this.props.audioTrack);
  80. if (this._ref) {
  81. const { _muted, _volume } = this.props;
  82. if (typeof _volume === 'number') {
  83. this._ref.volume = _volume;
  84. }
  85. if (typeof _muted === 'boolean') {
  86. this._ref.muted = _muted;
  87. }
  88. // @ts-ignore
  89. this._ref.addEventListener('error', this._errorHandler);
  90. }
  91. }
  92. /**
  93. * Remove any existing associations between the current audio track and the
  94. * component's audio element.
  95. *
  96. * @inheritdoc
  97. * @returns {void}
  98. */
  99. componentWillUnmount() {
  100. this._detachTrack(this.props.audioTrack);
  101. // @ts-ignore
  102. this._ref?.removeEventListener('error', this._errorHandler);
  103. }
  104. /**
  105. * This component's updating is blackboxed from React to prevent re-rendering of the audio
  106. * element, as we set all the properties manually.
  107. *
  108. * @inheritdoc
  109. * @returns {boolean} - False is always returned to blackbox this component
  110. * from React.
  111. */
  112. shouldComponentUpdate(nextProps: IProps) {
  113. const currentJitsiTrack = this.props.audioTrack?.jitsiTrack;
  114. const nextJitsiTrack = nextProps.audioTrack?.jitsiTrack;
  115. if (currentJitsiTrack !== nextJitsiTrack) {
  116. this._detachTrack(this.props.audioTrack);
  117. this._attachTrack(nextProps.audioTrack);
  118. }
  119. if (this._ref) {
  120. const currentVolume = this._ref.volume;
  121. const nextVolume = nextProps._volume;
  122. if (typeof nextVolume === 'number' && !isNaN(nextVolume) && currentVolume !== nextVolume) {
  123. this._ref.volume = nextVolume;
  124. }
  125. const currentMuted = this._ref.muted;
  126. const nextMuted = nextProps._muted;
  127. if (typeof nextMuted === 'boolean' && currentMuted !== nextMuted) {
  128. this._ref.muted = nextMuted;
  129. }
  130. }
  131. return false;
  132. }
  133. /**
  134. * Implements React's {@link Component#render()}.
  135. *
  136. * @inheritdoc
  137. * @returns {ReactElement}
  138. */
  139. render() {
  140. const { autoPlay, id } = this.props;
  141. return (
  142. <audio
  143. autoPlay = { autoPlay }
  144. id = { id }
  145. ref = { this._setRef } />
  146. );
  147. }
  148. /**
  149. * Calls into the passed in track to associate the track with the component's audio element.
  150. *
  151. * @param {Object} track - The redux representation of the {@code JitsiLocalTrack}.
  152. * @private
  153. * @returns {void}
  154. */
  155. _attachTrack(track?: ITrack) {
  156. if (!track?.jitsiTrack) {
  157. return;
  158. }
  159. track.jitsiTrack.attach(this._ref);
  160. this._play();
  161. }
  162. /**
  163. * Removes the association to the component's audio element from the passed
  164. * in redux representation of jitsi audio track.
  165. *
  166. * @param {Object} track - The redux representation of the {@code JitsiLocalTrack}.
  167. * @private
  168. * @returns {void}
  169. */
  170. _detachTrack(track?: ITrack) {
  171. if (this._ref && track && track.jitsiTrack) {
  172. clearTimeout(this._playTimeout);
  173. this._playTimeout = undefined;
  174. track.jitsiTrack.detach(this._ref);
  175. }
  176. }
  177. /**
  178. * Reattaches the audio track to the underlying HTMLAudioElement when an 'error' event is fired.
  179. *
  180. * @param {Error} error - The error event fired on the HTMLAudioElement.
  181. * @returns {void}
  182. */
  183. _errorHandler(error: Error) {
  184. logger.error(`Error ${error?.message} called on audio track ${this.props.audioTrack?.jitsiTrack}. `
  185. + 'Attempting to reattach the audio track to the element and execute play on it');
  186. this._detachTrack(this.props.audioTrack);
  187. this._attachTrack(this.props.audioTrack);
  188. }
  189. /**
  190. * Plays the underlying HTMLAudioElement.
  191. *
  192. * @param {number} retries - The number of previously failed retries.
  193. * @returns {void}
  194. */
  195. _play(retries = 0) {
  196. if (!this._ref) {
  197. // nothing to play.
  198. return;
  199. }
  200. const { autoPlay, id } = this.props;
  201. if (autoPlay) {
  202. // Ensure the audio gets play() called on it. This may be necessary in the
  203. // case where the local video container was moved and re-attached, in which
  204. // case the audio may not autoplay.
  205. this._ref.play()
  206. .then(() => {
  207. if (retries !== 0) {
  208. // success after some failures
  209. this._playTimeout = undefined;
  210. sendAnalytics(createAudioPlaySuccessEvent(id));
  211. logger.info(`Successfully played audio track! retries: ${retries}`);
  212. }
  213. }, e => {
  214. logger.error(`Failed to play audio track! retry: ${retries} ; Error: ${e}`);
  215. if (retries < 3) {
  216. this._playTimeout = window.setTimeout(() => this._play(retries + 1), 1000);
  217. if (retries === 0) {
  218. // send only 1 error event.
  219. sendAnalytics(createAudioPlayErrorEvent(id));
  220. }
  221. } else {
  222. this._playTimeout = undefined;
  223. }
  224. });
  225. }
  226. }
  227. /**
  228. * Sets the reference to the HTML audio element.
  229. *
  230. * @param {HTMLAudioElement} audioElement - The HTML audio element instance.
  231. * @private
  232. * @returns {void}
  233. */
  234. _setRef(audioElement: HTMLAudioElement | null) {
  235. this._ref = audioElement;
  236. }
  237. }
  238. /**
  239. * Maps (parts of) the Redux state to the associated {@code AudioTrack}'s props.
  240. *
  241. * @param {Object} state - The Redux state.
  242. * @param {Object} ownProps - The props passed to the component.
  243. * @private
  244. * @returns {IProps}
  245. */
  246. function _mapStateToProps(state: IReduxState, ownProps: any) {
  247. const { participantsVolume } = state['features/filmstrip'];
  248. return {
  249. _muted: state['features/base/config'].startSilent,
  250. _volume: participantsVolume[ownProps.participantId]
  251. };
  252. }
  253. export default connect(_mapStateToProps)(AudioTrack);