Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

AudioTrack.tsx 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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: React.RefObject<HTMLAudioElement>;
  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._ref = React.createRef();
  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?.current) {
  81. const audio = this._ref?.current;
  82. const { _muted, _volume } = this.props;
  83. if (typeof _volume === 'number') {
  84. audio.volume = _volume;
  85. }
  86. if (typeof _muted === 'boolean') {
  87. audio.muted = _muted;
  88. }
  89. // @ts-ignore
  90. audio.addEventListener('error', this._errorHandler);
  91. } else { // This should never happen
  92. logger.error(`The react reference is null for AudioTrack ${this.props?.id}`);
  93. }
  94. }
  95. /**
  96. * Remove any existing associations between the current audio track and the
  97. * component's audio element.
  98. *
  99. * @inheritdoc
  100. * @returns {void}
  101. */
  102. componentWillUnmount() {
  103. this._detachTrack(this.props.audioTrack);
  104. // @ts-ignore
  105. this._ref?.current?.removeEventListener('error', this._errorHandler);
  106. }
  107. /**
  108. * This component's updating is blackboxed from React to prevent re-rendering of the audio
  109. * element, as we set all the properties manually.
  110. *
  111. * @inheritdoc
  112. * @returns {boolean} - False is always returned to blackbox this component
  113. * from React.
  114. */
  115. shouldComponentUpdate(nextProps: IProps) {
  116. const currentJitsiTrack = this.props.audioTrack?.jitsiTrack;
  117. const nextJitsiTrack = nextProps.audioTrack?.jitsiTrack;
  118. if (currentJitsiTrack !== nextJitsiTrack) {
  119. this._detachTrack(this.props.audioTrack);
  120. this._attachTrack(nextProps.audioTrack);
  121. }
  122. if (this._ref?.current) {
  123. const audio = this._ref?.current;
  124. const currentVolume = audio.volume;
  125. const nextVolume = nextProps._volume;
  126. if (typeof nextVolume === 'number' && !isNaN(nextVolume) && currentVolume !== nextVolume) {
  127. if (nextVolume === 0) {
  128. logger.debug(`Setting audio element ${nextProps?.id} volume to 0`);
  129. }
  130. audio.volume = nextVolume;
  131. }
  132. const currentMuted = audio.muted;
  133. const nextMuted = nextProps._muted;
  134. if (typeof nextMuted === 'boolean' && currentMuted !== nextMuted) {
  135. logger.debug(`Setting audio element ${nextProps?.id} muted to true`);
  136. audio.muted = nextMuted;
  137. }
  138. }
  139. return false;
  140. }
  141. /**
  142. * Implements React's {@link Component#render()}.
  143. *
  144. * @inheritdoc
  145. * @returns {ReactElement}
  146. */
  147. render() {
  148. const { autoPlay, id } = this.props;
  149. return (
  150. <audio
  151. autoPlay = { autoPlay }
  152. id = { id }
  153. ref = { this._ref } />
  154. );
  155. }
  156. /**
  157. * Calls into the passed in track to associate the track with the component's audio element.
  158. *
  159. * @param {Object} track - The redux representation of the {@code JitsiLocalTrack}.
  160. * @private
  161. * @returns {void}
  162. */
  163. _attachTrack(track?: ITrack) {
  164. const { id } = this.props;
  165. if (!track?.jitsiTrack) {
  166. logger.warn(`Attach is called on audio element ${id} without tracks passed!`);
  167. return;
  168. }
  169. if (!this._ref?.current) {
  170. logger.warn(`Attempting to attach track ${track?.jitsiTrack} on AudioTrack ${id} without reference!`);
  171. return;
  172. }
  173. track.jitsiTrack.attach(this._ref.current)
  174. .catch((error: Error) => {
  175. logger.error(
  176. `Attaching the remote track ${track.jitsiTrack} to video with id ${id} has failed with `,
  177. error);
  178. })
  179. .finally(() => {
  180. this._play();
  181. });
  182. }
  183. /**
  184. * Removes the association to the component's audio element from the passed
  185. * in redux representation of jitsi audio track.
  186. *
  187. * @param {Object} track - The redux representation of the {@code JitsiLocalTrack}.
  188. * @private
  189. * @returns {void}
  190. */
  191. _detachTrack(track?: ITrack) {
  192. if (this._ref?.current && track && track.jitsiTrack) {
  193. clearTimeout(this._playTimeout);
  194. this._playTimeout = undefined;
  195. track.jitsiTrack.detach(this._ref.current);
  196. }
  197. }
  198. /**
  199. * Reattaches the audio track to the underlying HTMLAudioElement when an 'error' event is fired.
  200. *
  201. * @param {Error} error - The error event fired on the HTMLAudioElement.
  202. * @returns {void}
  203. */
  204. _errorHandler(error: Error) {
  205. logger.error(`Error ${error?.message} called on audio track ${this.props.audioTrack?.jitsiTrack}. `
  206. + 'Attempting to reattach the audio track to the element and execute play on it');
  207. this._detachTrack(this.props.audioTrack);
  208. this._attachTrack(this.props.audioTrack);
  209. }
  210. /**
  211. * Plays the underlying HTMLAudioElement.
  212. *
  213. * @param {number} retries - The number of previously failed retries.
  214. * @returns {void}
  215. */
  216. _play(retries = 0) {
  217. const { autoPlay, id } = this.props;
  218. if (!this._ref?.current) {
  219. // nothing to play.
  220. logger.warn(`Attempting to call play on AudioTrack ${id} without reference!`);
  221. return;
  222. }
  223. if (autoPlay) {
  224. // Ensure the audio gets play() called on it. This may be necessary in the
  225. // case where the local video container was moved and re-attached, in which
  226. // case the audio may not autoplay.
  227. this._ref.current.play()
  228. .then(() => {
  229. if (retries !== 0) {
  230. // success after some failures
  231. this._playTimeout = undefined;
  232. sendAnalytics(createAudioPlaySuccessEvent(id));
  233. logger.info(`Successfully played audio track! retries: ${retries}`);
  234. }
  235. }, e => {
  236. logger.error(`Failed to play audio track on audio element ${id}! retry: ${retries} ; Error:`, e);
  237. if (retries < 3) {
  238. this._playTimeout = window.setTimeout(() => this._play(retries + 1), 1000);
  239. if (retries === 0) {
  240. // send only 1 error event.
  241. sendAnalytics(createAudioPlayErrorEvent(id));
  242. }
  243. } else {
  244. this._playTimeout = undefined;
  245. }
  246. });
  247. }
  248. }
  249. }
  250. /**
  251. * Maps (parts of) the Redux state to the associated {@code AudioTrack}'s props.
  252. *
  253. * @param {Object} state - The Redux state.
  254. * @param {Object} ownProps - The props passed to the component.
  255. * @private
  256. * @returns {IProps}
  257. */
  258. function _mapStateToProps(state: IReduxState, ownProps: any) {
  259. const { participantsVolume } = state['features/filmstrip'];
  260. return {
  261. _muted: state['features/base/config'].startSilent,
  262. _volume: participantsVolume[ownProps.participantId]
  263. };
  264. }
  265. export default connect(_mapStateToProps)(AudioTrack);