我有一个类似的组件:
import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
class MovieList extends Component {
handlePress() {
// Play some sound here
}
render() {
const { movie } = this.props
return (
<TouchableOpacity onPress={this.handlePress.bind(this)}>
<View style={styles.movie}>
<Text style={styles.name}>{movie.name}</Text>
<View style={styles.start}>
<Text style={styles.text}>Start</Text>
</View>
</View>
</TouchableOpacity>
)
}
}
当我触摸view
时,我想播放一些声音。
我搜索了它,但没有找到任何适当的答案
当我按什么东西时,我能播放声音吗? 我怎么能这样做?
答案 0 :(得分:13)
查看React Native Sound - 用于访问设备音频控件的跨平台组件。
您可以像这样使用它:
const Sound = require('react-native-sound')
let hello = new Sound('hello.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log(error)
}
})
hello.play((success) => {
if (!success) {
console.log('Sound did not play')
}
})
答案 1 :(得分:7)
答案 2 :(得分:0)
您可以像这样通过expo-av
库播放声音。
import { Audio } from "expo-av";
class MovieList extends Component {
async handlePress() {
try {
const { sound: soundObject, status } = await
Audio.Sound.createAsync('sound.mp3', { shouldPlay: true });
await soundObject.playAsync();
} catch (error) { console.log(error); }
}
render() {
const { movie } = this.props
return (
<TouchableOpacity onPress={this.handlePress.bind(this)}>
<View style={styles.movie}>
<Text style={styles.name}>{movie.name}</Text>
<View style={styles.start}>
<Text style={styles.text}>Start</Text>
</View>
</View>
</TouchableOpacity>
)
}
}