React Native使用expo-av传递mp3为组件参数报错如何解决?
你代码存在两处核心问题,修改后即可正常运行:
- 遗漏await关键字:
Audio.Sound.createAsync是异步方法,必须加await等待实例创建完成才能拿到正确的sound对象,否则返回的是Promise,解构会报错。 - 传参格式错误:
createAsync方法接收的音频源参数如果是本地require的资源,直接传递资源值即可,不需要封装为{mp3: 资源}的对象结构,你之前硬编码路径时因为直接传了require的返回值所以运行正常,改成参数传递时搞错了结构。
修正后的 SoundPlayer 组件代码
import * as React from 'react'; import { Text, View, StyleSheet, Button } from 'react-native'; import { Audio } from 'expo-av'; function SoundPlayer({ mp3 }) { const [sound, setSound] = React.useState(); async function playSound() { try { console.log('Loading Sound'); // 修正点:加await、直接传递mp3参数不封装对象 const { sound: newSound } = await Audio.Sound.createAsync(mp3); setSound(newSound); console.log('Playing Sound'); await newSound.playAsync(); } catch (err) { console.log('播放出错:', err) } } React.useEffect(() => { return sound ? () => { console.log('Unloading Sound'); sound.unloadAsync(); } : undefined; }, [sound]); return ( <View style={styles.container}> <Button title="Play Sound" onPress={playSound} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center' } }) export default SoundPlayer
App 页面代码无需修改,直接正常传入require的本地音频资源即可。如果后续需要播放远程音频,传入{uri: 远程音频链接}格式的对象即可。
内容的提问来源于stack exchange,提问作者Viswajith Kumar
相关产品推荐
相关产品推荐

