links: React Native MOC


When you want to grab the attention of a user after doing some action, audio feedback might be a good way

In order to play sounds in react native there are some good libraries like

  1. React Native sound
  2. React Native Audio Toolkit from React Native Community
  3. Expo AV if you have Expo SDK installed

Let’s use React Native Sound as has a lot of stars and has recent commits

Installation

Add the dependency to your package.json

yarn add react-native-sound

Android

Add the sound you want to play under the directory android/app/src/main/res/raw

iOS

Usage

Create a reusable model for initializing, playing and releasing Sound

import Sound from 'react-native-sound';
 
export class SoundModel {
  sound?: Sound;
  isLoaded = false;
 
  constructor() {
    Sound.setCategory('Playback');
  }
 
  initialize() {
    if (!this.sound) {
      this.sound = new Sound('ding.mp3', Sound.MAIN_BUNDLE, (error) => {
        if (error) {
          this.isLoaded = false;
        } else {
          this.isLoaded = true;
        }
      });
    }
  }
 
  play() {
    if (this.isLoaded) {
      this.sound?.play();
    }
  }
 
  release() {
    this.sound?.release();
  }
}
 

React Native Sound provides multiple categories like Alarm , Playback etc

We can go with Playback

Now in your React Native component all you need to do is

import React from 'react';
 
const SomeComponent = () => {
  const soundModel = React.useRef(new SoundModel()).current
 
  useEffect(() => {
    soundModel.initialize()
 
    return soundModel.release
  })
 
  const handlePress = () => {
    soundModel.play()
  }
 
  return (
    <>
      <Button onPress={handlePress} title={'Play'} />
    </>
  )
}
 

That’s it 🔥


tags: sound react-native