How to play sound (mp3) in React Native?

眉间皱痕 提交于 2020-07-22 05:34:36

问题


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>


回答1:


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



回答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 ? 
  <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}


来源:https://stackoverflow.com/questions/62623602/how-to-play-sound-mp3-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!