如何在 React Native 中播放声音(mp3)?

IT技术 javascript reactjs react-native mobile
2021-05-28 14:10:00

我想为我的项目制作音频播放器。我不知道如何使用 TouchableOpacity 播放音频。我想播放音频,但是当我按下播放图标(按钮)时,它必须更改为暂停图标(按钮)。我需要一些循环解决方案。我怎样才能使用它?

                    <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>

2个回答

这是导入:

import React from "react";
import { Text, View, TouchableOpacity } from "react-native";
import { WebView } from "react-native-webview";

然后我使用了 WebView :

export default class App extends React.Component {
  render() {
    return (
      <View>
        <TouchableOpacity
          style={{ marginTop: 50 }}
          onPress={() => {
            this.webview.injectJavaScript(
              'document.getElementById("audio").play();'
            );
          }}
        >

这是播放按钮:

          <Text>Play</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={{ marginTop: 50 }}
          onPress={() => {
            this.webview.injectJavaScript(
              'document.getElementById("audio").pause();'
            );
          }}
        >

这是暂停按钮: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>
    );
  }
}

我建议是这样的:

一开始你必须创建一个变量:

const [isPlaying, setIsPlaying] = useState(false)

在您的可触摸使用中:

{ !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}