I want to play a sound in React Native.
I have try to read here in zmxv/react-native-sound, but as a beginner like me, that's documentation make me confused how to apply that in React Native code.
Before I have try this one to make react native play sound on event and make a code like this:
import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
const Sound = require('react-native-sound')
export default class MovieList extends Component {
handlePress() {
// Play some sound here
let hello = new Sound('motorcycle.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log(error)
}
})
hello.play((success) => {
if (!success) {
console.log('Sound did not play')
}
})
}
render() {
const { movie } = this.props
return (
<TouchableOpacity onPress={this.handlePress.bind(this)}>
<View>
<Text>Start</Text>
</View>
</TouchableOpacity>
)
}
}
And this is where I put my audio:
MyProject/android/app/src/main/res/raw/motorcycle.mp3
Project structure
So, what's wrong in my code?
try { const { sound: soundObject, status } = await Audio. Sound. createAsync( require('./assets/sounds/hello. mp3'), { shouldPlay: true } ); // Your sound is playing! }
This will preload the sound and when you press the play button it will play it.
export default class MovieList extends Component {
componentDidMount(){
this.hello = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
}
handlePress() {
this.hello.play((success) => {
if (!success) {
console.log('Sound did not play')
}
})
}
render() {
const { movie } = this.props
return (
<TouchableOpacity onPress={this.handlePress.bind(this)}>
<View>
<Text>Start</Text>
</View>
</TouchableOpacity>
)
}
}
If you are looking to play sound tracks from a list of sounds please check this gist for detailed code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With