How to Implement Play Sound in React Native?
Published On: 04/07/2022 | Category:
React Native
Hi Guys,
In this tute, we will discuss how to implement play sound in react native. This post will give you simple example of how to play sound in react native. This article will give you simple example of play sound example in react native. I explained simply about how to use play sound in react native. you will do the following things for how to create play sound in react native.
Let's start following example:
Step 1: Download ProjectIn the first step run the following command to create a project.
expo init ExampleAppStep 2: Install and Setup
In this step, you can install expo-av:
expo install expo-avStep 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...