Home > Mobile >  Trying to pass an mp3 file as a parameter in React Native and I am getting errors. How can I resolve
Trying to pass an mp3 file as a parameter in React Native and I am getting errors. How can I resolve

Time:10-03

I am currently building an app where I want there to be a play button that when pressed plays an audio file. My method of doing so is to create a soundplayer component that creates the button and audio sync so that I can just call the component in the main screen I use it in. I can get the soundplayer component to work just fine when I manually put the mp3 file path in it's proper place, but not when I try to pass it in as a parameter. Take a look at my code below and see if you may be able to help resolve the situation.

SoundPlayer Component

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

App Screen

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

CodePudding user response:

According to the Documentation of expo-av, we can see that there are two different methods for static files and remote files to load.

For Static Files (require...) this is the way to load a file

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

For Remote Files (https://example.com/test.mp3) this is the way to load a file

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

So replacing,

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

with

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

Should fix the issue. Just make sure the location of the sound file is correct.


Another Approach

A better way to load and play audio files, which I personally feel the best is to use useRef variable for the sound instance. I've created a snack for the implementation here

  • Related