Pull to refresh and button press sound effect in React Native

In this post I will show you how to add sound to button press and “pull to refresh” similar to the Facebook and Twitter app. For this I will use an npm library called react-native-sound.

What is react-native-sound?

This is a React Native library for playing sound clips on iOS, Android, and Windows.

How to install?

In your existing React Native project you will have to run the install command npm install react-native-sound --save then to link it to your project react-native link react-native-sound

How to use?

You can create a helper file audio.js which will import the library then export a couple of methods for different sounds.

  
  
import Sound from 'react-native-sound';

Sound.setCategory('Ambient', true);

const buttonPress = new Sound(require('../audio/button.mp3'), error => console.log(error));
export const playButtonPress = () => {
  buttonPress.play((success) => buttonPress.reset());
}

const playListPull = new Sound(require('../audio/pull.mp3'), error => console.log(error));
export const playListPull = () => {
  pull.play((success) => pull.reset());
}

const playListPullFinished = new Sound(require('../audio/pullFinished.mp3'), error => console.log(error));
export const playListPullFinished = () => {
  pullFinished.play((success) => pullFinished.reset());
}
  

You can find the full list of options here. Please make sure you include Sound.setCategory('Ambient', true); because in iOS by default it will stop your music and play the sound. Adding this line at the top will play the sound even though there is music playing.

Now that you have the helper file, you can import the methods you want to call like this:

  
  
import React, { Component } from 'react';
import {
  TouchableOpacity,
  Text,
} from 'react-native';
import { playButtonPress } from '../helpers/audio';

export default class MyButton extends Component {
  render() {
    return (
      <TouchableOpacity onPress={playButtonPress}>
        <Text>Click me</Text>
      </TouchableOpacity>
    );
  }
}
  

Andy

Front-end Engineer & Designer based in Dublin currently working @IBM.
I write about: Javascript, HTML, CSS, React JS, React Native and UI/UX Design.

Add comment