简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM