Search code examples
javascriptreact-nativeaudioexpoexpo-av

Stop Audio expo-av - React Native Expo


I am using Audio from expo-av in react-native-expo.

I can run the audio using loadAsync method on Audio.sound contructor.

Although when I try to stop the voice it doesn't stop the voice.

Following is the minimalistic code snippet. Is this the correct way to stop the sound. I am not able to find the solution for this.

import React, {useState,  useEffect} from 'react';
import {  Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  const [audioStatus, setAudioStatus] = useState(false)
  const sound = new Audio.Sound();
  
  useEffect(()=>{
    (async () => {
            console.log('status', audioStatus)
            if (audioStatus) {
                await sound.loadAsync('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
                try {
                    await sound.playAsync()
                } catch (e) {
                    console.log(e)
                }
            }else {
                await sound.stopAsync()
                await sound.unloadAsync()
            }
          })()
  },[audioStatus])
  
  return (
      <Button color={audioStatus ? 'red' : 'green'} title={'play'} onPress={()=>setAudioStatus(!audioStatus)} />
  );
}

Thanks in Advance


Solution

  • This is a React problem. Each time your component renders, the sound variable is being reset to a new, not-yet-loaded Audio.Sound object. Here, sound should be part of the state of the component. You can change the line:

    const sound = new Audio.Sound();
    

    to

    const [sound, setSound] = useState(new Audio.Sound());
    

    and it will work.

    Expo Snack