Как воспроизвести звук в React Native? - PullRequest
0 голосов
/ 12 декабря 2018

Я хочу воспроизвести звук в React Native.

Я пытаюсь прочитать здесь в zmxv / реагировать-нативный звук , но как начинающий, как я, это документацияменя смутило, как применить это в коде React Native.

Прежде чем я попробую этот , чтобы заставить звуковой сигнал реагировать на событие и создать код, подобный этому:

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

И вот куда я положил свое аудио:

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

Структура проекта

Project Structure

Итак, что не так в моем коде?

Ответы [ 3 ]

0 голосов
/ 12 декабря 2018

Это предварительно загрузит звук, и когда вы нажмете на воспроизведение, он будет воспроизводить его.

   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>
        )
    }
}
0 голосов
/ 12 декабря 2018

Большое спасибо, у кого есть ответ на этот вопрос, но я решил это с помощью этого простого:

import React, { Component } from 'react'
import { Text, View, TouchableOpacity } from 'react-native'
import Sound from 'react-native-sound';

export default class MovieList extends Component {

    sound = new Sound('motorcycle.mp3');

    playSound = () => {
        this.sound.play()
    }

    render() {
        return (
            <View>
                <TouchableOpacity onPress={this.playSound}>
                    <View>
                        <Text>Start</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
}
0 голосов
/ 12 декабря 2018

Попробуйте этот код для воспроизведения звука:

setTimeout(() => {
     var sound = new Sound("motorcycle.mp3",Sound.MAIN_BUNDLE, (error) => {
                     /* ... */
     });

     setTimeout(() => {
         sound.play((success) => {
                  /* ... */
         });
    }, 100);
}, 100);

Это взломано и решено https://github.com/zmxv/react-native-sound/issues/89#issuecomment-276678935

...