React Native Play Sound Example

Jul 04, 2022 . Admin

Hi Guys,

I am going to explain you example of how to play sound in react native. We will use how to create play sound in react native. we will help you to give example of how to use play sound in react native. I explained simply step by step how to implement play sound in react native. You just need to some step to done play sound example in react native.

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