You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Audio.ts 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import Sound from 'react-native-sound';
  2. import logger from '../../logger';
  3. import AbstractAudio from '../AbstractAudio';
  4. /**
  5. * The React Native/mobile {@link Component} which is similar to Web's
  6. * {@code HTMLAudioElement} and wraps around react-native-webrtc's
  7. * {@link RTCView}.
  8. */
  9. export default class Audio extends AbstractAudio {
  10. /**
  11. * Reference to 'react-native-sound} {@link Sound} instance.
  12. */
  13. _sound: Sound | undefined | null;
  14. /**
  15. * A callback passed to the 'react-native-sound''s {@link Sound} instance,
  16. * called when loading sound is finished.
  17. *
  18. * @param {Object} error - The error object passed by
  19. * the 'react-native-sound' library.
  20. * @returns {void}
  21. * @private
  22. */
  23. _soundLoadedCallback(error: Error) {
  24. if (error) {
  25. logger.error('Failed to load sound', error);
  26. } else {
  27. this.setAudioElementImpl(this._sound);
  28. }
  29. }
  30. /**
  31. * Will load the sound, after the component did mount.
  32. *
  33. * @returns {void}
  34. */
  35. componentDidMount() {
  36. this._sound
  37. = this.props.src
  38. ? new Sound(
  39. this.props.src, undefined,
  40. this._soundLoadedCallback.bind(this))
  41. : null;
  42. }
  43. /**
  44. * Will dispose sound resources (if any) when component is about to unmount.
  45. *
  46. * @returns {void}
  47. */
  48. componentWillUnmount() {
  49. if (this._sound) {
  50. this._sound.release();
  51. this._sound = null;
  52. this.setAudioElementImpl(null);
  53. }
  54. }
  55. /**
  56. * Attempts to begin the playback of the media.
  57. *
  58. * @inheritdoc
  59. * @override
  60. */
  61. play() {
  62. if (this._sound) {
  63. this._sound.setNumberOfLoops(this.props.loop ? -1 : 0);
  64. this._sound.play(success => {
  65. if (!success) {
  66. logger.warn(`Failed to play ${this.props.src}`);
  67. }
  68. });
  69. }
  70. }
  71. /**
  72. * Implements React's {@link Component#render()}.
  73. *
  74. * @inheritdoc
  75. * @returns {null}
  76. */
  77. render() {
  78. // TODO react-native-webrtc's RTCView doesn't do anything with the audio
  79. // MediaStream specified to it so it's easier at the time of this
  80. // writing to not render anything.
  81. return null;
  82. }
  83. /**
  84. * Stops the sound if it's currently playing.
  85. *
  86. * @returns {void}
  87. */
  88. stop() {
  89. if (this._sound) {
  90. this._sound.stop();
  91. }
  92. }
  93. }