[英]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.
我不知道如何使用 TouchableOpacity 播放音频。 I want to play audio but when I press on play icon (button) it have to be changed to pause icon (button).
我想播放音频,但是当我按下播放图标(按钮)时,必须将其更改为暂停图标(按钮)。 And I need some solution for loop.
我需要一些循环解决方案。 How can I use it?
我该如何使用它?
<TouchableOpacity style={styles.playButtonContainer}>
<Ionicons name="ios-play" size={75} color="#000" />
<Ionicons name="ios-pause" size={75} color="#000" />
</TouchableOpacity>
<TouchableOpacity>
<Entypo name="loop" size={40} color="#000"></Entypo>
</TouchableOpacity>
Here is import:这里是进口:
import React from "react";
import { Text, View, TouchableOpacity } from "react-native";
import { WebView } from "react-native-webview";
Then I used WebView:然后我使用了 WebView:
export default class App extends React.Component {
render() {
return (
<View>
<TouchableOpacity
style={{ marginTop: 50 }}
onPress={() => {
this.webview.injectJavaScript(
'document.getElementById("audio").play();'
);
}}
>
Here is Play button:这是播放按钮:
<Text>Play</Text>
</TouchableOpacity>
<TouchableOpacity
style={{ marginTop: 50 }}
onPress={() => {
this.webview.injectJavaScript(
'document.getElementById("audio").pause();'
);
}}
>
Here is Pause button: enter code here
这是暂停按钮:
enter code here
<Text>Pause</Text>
</TouchableOpacity>
<WebView
ref={(ref) => (this.webview = ref)}
originWhitelist={["*"]}
mediaPlaybackRequiresUserAction={false} // Allow autoplay
useWebKit={true}
source={{
html:
'<audio id="audio" loop> <source src="https://go.transportili.app/static/sounds/ring.mp3" type="audio/mp3" /> </audio>',
}}
/>
</View>
);
}
}
I suggest something like this:我建议这样的事情:
In the begining you must create a variable:在开始时,您必须创建一个变量:
const [isPlaying, setIsPlaying] = useState(false)
in your touchable use this:在你的可触摸使用这个:
{ !isPlaying ?
<TouchableOpacity style={styles.playButtonContainer} onClick={setIsPlaying(true)}>
<Ionicons name="ios-play" size={75} color="#000" />
</TouchableOpacity>
: null;}
{ isPlaying ?
<TouchableOpacity style={styles.playButtonContainer} onClick={setIsPlaying(false)>
<Ionicons name="ios-pause" size={75} color="#000" />
</TouchableOpacity>
: null}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.