如何在React Native中播放声音? [英] How to play sound in React Native?
问题描述
我想在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中播放声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!