react-native
  1. react-native-sound

React-Native Sound

Syntax

The react-native-sound library can be used to play audio files in React Native.

import Sound from 'react-native-sound';

const sound = new Sound('file.mp3', Sound.MAIN_BUNDLE, error => {
  if (error) {
    console.error('Failed to load sound', error);
    return;
  }
  // loaded successfully
  sound.play();
});

Example

import React from 'react';
import { Button } from 'react-native';
import Sound from 'react-native-sound';

const sound = new Sound('file.mp3', Sound.MAIN_BUNDLE, error => {
  if (error) {
    console.error('Failed to load sound', error);
    return;
  }
});

const PlaySoundButton = () => {
  const handlePress = () => {
    sound.play();
  }
  
  return (
    <Button title="Play Sound" onPress={handlePress} />
  );
}

export default PlaySoundButton;

Output

When the PlaySoundButton is pressed, the audio file specified in the Sound constructor will play.

Explanation

The react-native-sound library provides a Sound object that can be used to play audio files. The Sound constructor takes three arguments: the path to the audio file, the bundle reference (usually Sound.MAIN_BUNDLE), and a callback function that will be called when the sound is loaded.

Once the sound is loaded, it can be played using the play method of the Sound object.

Use

The react-native-sound library can be used in any React Native component to play audio files.

Some common methods that can be used with the Sound object include:

  • play: Plays the audio file.
  • pause: Pauses the audio file.
  • stop: Stops the audio file.
  • release: Releases the resources used by the Sound object.

Important Points

  • The audio file must be included in the app bundle, or downloaded to the device before it can be played by react-native-sound.
  • The Sound object can only play one audio file at a time. To play multiple sounds simultaneously, multiple Sound objects must be used.
  • The react-native-sound library supports iOS and Android platforms.

Summary

react-native-sound is a powerful library for playing audio files in React Native. By using the Sound object to load and play audio files, developers can create engaging audio experiences in their apps.

Published on: