我有一个像这样的组件:
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
时,我想播放一些声音。
我已经用谷歌搜索过但没有找到任何合适的答案
当我按下某个东西时,是否可以播放声音? 我该怎么做?
查看 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')
}
})
您可以像这样使用
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>
)
}
}
首先尝试使用互联网上的 mp3 文件,看看它是否正常工作,然后尝试从本地资产文件夹导入/需要。
Working solution as of 2024-11:
yarn add react-native-sound
function App(){
const Sound = require('react-native-sound');
console.log(Sound);//should turn a Funciton in your console
var audio = new Sound(
'https://file-examples.com/storage/fe00d37cde6728af4966ebc/2017/11/file_example_MP3_700KB.mp3',
null,
error => {
if (error) {
console.log('failed to load the sound', error);
return;
}
// if loaded successfully
console.log(
'duration in seconds: ' +
audio.getDuration() +
'number of channels: ' +
audio.getNumberOfChannels(),
);
audio.play();
/*
audio.pause();
audio.isPlaying()
*/
},
);
}