How To Play Sound (mp3) In React Native?
I want to make audio player for my project. I dont know how to play audio with TouchableOpacity. I want to play audio but when I press on play icon (button) it have to be changed t
Solution 1:
Here is import :
importReactfrom"react";
import { Text, View, TouchableOpacity } from"react-native";
import { WebView } from"react-native-webview";
Then I used WebView :
exportdefaultclassAppextendsReact.Component {
render() {
return (
<View>
<TouchableOpacitystyle={{marginTop:50 }}
onPress={() => {
this.webview.injectJavaScript(
'document.getElementById("audio").play();'
);
}}
>
Here is Play button:
<Text>Play</Text></TouchableOpacity><TouchableOpacitystyle={{marginTop:50 }}
onPress={() => {
this.webview.injectJavaScript(
'document.getElementById("audio").pause();'
);
}}
>
Here is Pause button :enter code here
<Text>Pause</Text></TouchableOpacity><WebViewref={(ref) => (this.webview = ref)}
originWhitelist={["*"]}
mediaPlaybackRequiresUserAction={false} // Allow autoplay
useWebKit={true}
source={{
html:
'<audioid="audio"loop><sourcesrc="https://go.transportili.app/static/sounds/ring.mp3"type="audio/mp3" /></audio>',
}}
/>
</View>
);
}
}
Solution 2:
I suggest something like this:
In the begining you must create a variable:
const [isPlaying, setIsPlaying] = useState(false)
in your touchable use this:
{ !isPlaying ?
<TouchableOpacitystyle={styles.playButtonContainer}onClick={setIsPlaying(true)}><Ioniconsname="ios-play"size={75}color="#000" /></TouchableOpacity>
: null;}
{ isPlaying ?
<TouchableOpacitystyle={styles.playButtonContainer}onClick={setIsPlaying(false)><Ioniconsname="ios-pause"size={75}color="#000" /></TouchableOpacity>
: null}
Post a Comment for "How To Play Sound (mp3) In React Native?"