Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - How to play sound in React Native?

I want to play a sound in React Native.

I have try to read here in zmxv/react-native-sound, but as a beginner like me, that's documentation make me confused how to apply that in React Native code.

Before I have try this one to make react native play sound on event and make a code like this:

import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
const Sound = require('react-native-sound')


export default class MovieList extends Component {

    handlePress() {
        // Play some sound here
        let hello = new Sound('motorcycle.mp3', Sound.MAIN_BUNDLE, (error) => {
            if (error) {
              console.log(error)
            }
          })

          hello.play((success) => {
            if (!success) {
              console.log('Sound did not play')
            }
          })
    }

    render() {
        const { movie } = this.props
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this)}>
                <View>
                      <Text>Start</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

And this is where I put my audio:

MyProject/android/app/src/main/res/raw/motorcycle.mp3

Project structure

Project Structure

So, what's wrong in my code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This will preload the sound and when you press the play button it will play it.

export default class MovieList extends Component {
    componentDidMount(){
      this.hello = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
        if (error) {
          console.log('failed to load the sound', error);
          return;
        }
      });
    }
    
    
    handlePress() {
      this.hello.play((success) => {
        if (!success) {
          console.log('Sound did not play')
        }
      })
    }

    render() {
        const { movie } = this.props
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this)}>
                <View>
                      <Text>Start</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

If you are looking to play sound tracks from a list of sounds please check this gist for detailed code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...