tul56352
tul56352

Reputation: 107

Stop Current Sound when another is pressed React Native Expo

Im having trouble trying to stop the current playing sound when another Sound is pressed without having to pause the current Sound in react Native Expo. Note: I can pause and play the Sound perfectly. So basically like a normal music player if that is overlapping when pressing another song.


const SampleTrack = {uri:'https://firebasestorage.googleapisro-b97ec.appspot.com/o/song%201.mp3?a9'}

const FirstP = () => { 
  const [Loaded, SetLoaded] = React.useState(false);
  const [Loading, SetLoading] = React.useState(false);
  
  const sound = React.useRef(new Audio.Sound());
  
  React.useEffect(() => {
    LoadAudio();
  }, []);
 
  
   const PlayAudio = async () => {
    try {
      const result = await sound.current.getStatusAsync();
      if (result.isLoaded) {
        if (result.isPlaying === false) {
          sound.current.playAsync();
        }
      }
    } catch (error) {}
  };

  const PauseAudio = async () => {
    try {
      const result = await sound.current.getStatusAsync();
      if (result.isLoaded) {
        if (result.isPlaying === true) {
          sound.current.pauseAsync();
        }
      }
    } catch (error) {}
  };

  const LoadAudio = async () => {
    SetLoading(true);
    const checkLoading = await sound.current.getStatusAsync();
    if (checkLoading.isLoaded === false) {
      try {
        const result = await sound.current.loadAsync(SampleTrack, {}, true);
        if (result.isLoaded === false) {
          SetLoading(false);
          console.log('Error in Loading Audio');
        } else {
          SetLoading(false);
          SetLoaded(true);
        }
      } catch (error) {
        console.log(error);
        SetLoading(false);
      }
    } else {
      SetLoading(false);
    }
  };

if anyone can help that would be great.

Upvotes: 2

Views: 1929

Answers (1)

Kartikey
Kartikey

Reputation: 4992

Here's a complete Audio Player with Play/Pause/Load/Next/Previous feature.

Working Example

import * as React from 'react';
import {
  Text,
  View,
  StyleSheet,
  ActivityIndicator,
  Button,
} from 'react-native';
import Constants from 'expo-constants';
import { Audio } from 'expo-av';

const Tracks = [
  {
    id: 0,
    track: require('./Roses.m4a'),
  },
  {
    id: 1,
    track: require('./Poison.m4a'),
  },
  {
    id: 2,
    track: require('./Alone.m4a'),
  },
];

export default function App() {
  const [Loaded, SetLoaded] = React.useState(false);
  const [Loading, SetLoading] = React.useState(false);
  const [CurrentSong, SetCurrentSong] = React.useState(Tracks[0]);
  const sound = React.useRef(new Audio.Sound());

  React.useEffect(() => {
    LoadAudio();

    return () => Unload();
  }, [CurrentSong]);

  const Unload = async () => {
    await sound.current.unloadAsync();
  };

  const PlayAudio = async () => {
    try {
      const result = await sound.current.getStatusAsync();
      if (result.isLoaded) {
        if (result.isPlaying === false) {
          sound.current.playAsync();
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

  const PauseAudio = async () => {
    try {
      const result = await sound.current.getStatusAsync();
      if (result.isLoaded) {
        if (result.isPlaying === true) {
          sound.current.pauseAsync();
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

  const LoadAudio = async () => {
    SetLoaded(false);
    SetLoading(true);
    const checkLoading = await sound.current.getStatusAsync();
    if (checkLoading.isLoaded === false) {
      try {
        const result = await sound.current.loadAsync(
          CurrentSong.track,
          {},
          true
        );
        if (result.isLoaded === false) {
          SetLoading(false);
          console.log('Error in Loading Audio');
        } else {
          SetLoading(false);
          PlayAudio();
          SetLoaded(true);
        }
      } catch (error) {
        console.log(error);
        SetLoading(false);
      }
    } else {
      SetLoading(false);
    }
  };

  const NextSong = () => {
    if (CurrentSong.id === Tracks[Tracks.length - 1].id) {
      SetCurrentSong(Tracks[0]);
    } else {
      SetCurrentSong(Tracks[CurrentSong.id + 1]);
    }
  };

  const PrevSong = () => {
    if (CurrentSong.id === 0) {
      SetCurrentSong(Tracks[Tracks.length - 1]);
    } else {
      SetCurrentSong(Tracks[CurrentSong.id - 1]);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.AudioPLayer}>
        {Loading === true ? (
          <ActivityIndicator size={'small'} color={'red'} />
        ) : (
          <>
            <Button title="Play Song" onPress={PlayAudio} />
            <Button title="Pause Song" onPress={PauseAudio} />
            <Text>Currently Playing : {CurrentSong.id}</Text>
            <Button title="Next Song" onPress={NextSong} />
            <Button title="Previous Song" onPress={PrevSong} />
          </>
        )}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  AudioPLayer: {
    width: '100%',
    height: 50,
    alignItems: 'center',
  },
});

Upvotes: 2

Related Questions