我想在React Native中播放声音.
我已经尝试在
那么,我的代码有什么问题?
解决方案这将预加载声音,当您按播放时将播放声音.
导出默认类MovieList扩展Component {componentDidMount(){this.hello = new Sound('whoosh.mp3',Sound.MAIN_BUNDLE,(error)=> {如果(错误){console.log('无法加载声音',错误);返回;}});}handlePress(){this.hello.play((success)=> {如果(!成功){console.log('声音没有播放')}})}使成为() {const {movie} = this.props返回 (< TouchableOpacity onPress = {this.handlePress.bind(this)}><查看><文本>开始</文本></View></TouchableOpacity>)}}
如果您要从声音列表中播放音轨,请检查有关详细信息的gitHub链接代码
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
So, what's wrong in my code?
解决方案This will preload the sound and When you press the play 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 Track from a List of sounds please check this gitHub gist link for detailed code
更多推荐
如何在React Native中播放声音?
发布评论