尝试在 React Native 中将 mp3 文件作为参数传递时出现错误。我该如何解决这个问题?我正在使用 Expo-av 作为参考

Trying to pass an mp3 file as a parameter in React Native and I am getting errors. How can I resolve this problem? I am using Expo-av for reference

我目前正在构建一个应用程序,我希望其中有一个播放按钮,按下该按钮可播放音频文件。我这样做的方法是创建一个声音播放器组件,它创建按钮和音频同步,这样我就可以在我使用它的主屏幕中调用该组件。当我手动放置时,我可以让声音播放器组件正常工作mp3 文件路径在适当的位置,但当我尝试将其作为参数传递时却没有。看看我下面的代码,看看你是否能帮助解决这个问题。

声音播放器组件

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() {
    console.log('Loading Sound');
    const { sound } =  Audio.Sound.createAsync({ mp3 });
    setSound(sound);

    console.log('Playing Sound');
    await sound.playAsync(); }

  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

应用程序屏幕

export default function App() {
  return (
    <SoundPlayer  mp3 = {require('/Users/viswajithkumar/DharmaWorldwide/Screens/assets/Audio/FrenchTouch.mp3')}/>
  );
}

根据expo-av的Documentation,我们可以看到加载静态文件和远程文件有两种不同的方法。

对于静态文件(需要...)这是加载文件的方式

const { sound } = await Audio.Sound.createAsync(require('./assets/Hello.mp3'));

对于远程文件(https://example.com/test.mp3)这是加载文件的方式

const { sound } = await Audio.Sound.createAsync({
  uri: 'https://example.com/test.mp3',
});

所以替换,

const { sound } =  Audio.Sound.createAsync({ mp3 });

const { sound } =  Audio.Sound.createAsync(mp3);

应该可以解决问题。只要确保声音文件的 location 正确即可。


另一种方法

加载和播放音频文件的更好方法,我个人认为最好的方法是对声音实例使用 useRef 变量。我为实现创建了一个小吃 here