How to Play Sound in React Native?

Jul 04, 2022

.

Admin

How to Play Sound in React Native?

Hi Guys,

This article will provide some of the most important example how to create play sound in react native. if you want to see example of how to play sound in react native then you are a right place. you can see how to implement play sound in react native. This article will give you simple example of how to use play sound in react native. Here, Creating a basic example of react native play sound example.

Let's start following example:

Step 1: Download Project


In the first step run the following command to create a project.

expo init ExampleApp

Step 2: Install and Setup

In this step, you can install expo-av:

expo install expo-av

Step 3: App.js

In this step, You will open the App.js file and put the code.

import * as React from 'react';

import { View, StyleSheet, Button } from 'react-native';

import { Audio } from 'expo-av';

const App = () => {

const [sound, setSound] = React.useState();

const playSound = async () => {

const { sound } = await Audio.Sound.createAsync(

require('./assets/Hello.mp3')

);

setSound(sound);

await sound.playAsync();

}

const stopSound = async () => {

await sound.stopAsync()

}

React.useEffect(() => {

return sound

? () => {

sound.unloadAsync();

}

: undefined;

}, [sound]);

return (

<View style={styles.container}>

<Button title="Play Sound" onPress={playSound} />

<View style={{ marginTop:10 }}>

<Button title="Stop Sound" onPress={stopSound} />

</View>

</View>

);

}

const styles = StyleSheet.create({

container: {

flex: 1,

justifyContent: 'center',

alignItems:'center',

padding: 10,

},

});

export default App;

Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output :

It will help you...

#React Native