Problem while using Expo-av Library, App crashes while changing the songs

Viewed 175

I am running my application on an android device. So I am using Context API, the song is in context, whenever a user clicks on a song it is updated in context and every component gets it and then useEffect of PlayerWidget gets triggered and that time my app is crashing. At the Start of the app, the song is null.

import React, { useEffect, useState, useContext } from "react";
import { View, Text, Image, TouchableOpacity } from "react-native";
import tailwind from "tailwind-rn";
import { AntDesign, FontAwesome, Foundation } from "@expo/vector-icons";
import { Audio } from "expo-av";
import { Sound } from "expo-av/build/Audio/Sound";
import { AppContext } from "../AppContext";

function PlayerWidget() {
  const { song } = useContext(AppContext);
  useEffect(() => {
    if (song) {
      console.log("player", song);
      console.log("a");
      playCurrentSong();
    }
  }, [song]);

  //const navigation = useNavigation();
  const [sound, setSound] = (useState < Sound) | (null > null);
  const [isPlaying, setIsPlaying] = useState < boolean > false;
  const [duration, setDuration] = (useState < number) | (null > null);
  const [position, setPosition] = (useState < number) | (null > null);

  /* useEffect(() => {
    playCurrentSong();
  }, []);
   */
  const playBackStatusUpdate = (status: any) => {
    setPosition(status.positionMillis);
    setDuration(status.durationMillis);
  };

  const playCurrentSong = async () => {
    if (!song) return;
    if (sound) {
      console.log(sound);
      await sound.unloadAsync();
    }
    const { sound: newSound } = await Audio.Sound.createAsync(
      { uri: song.songUri },
      { shouldPlay: isPlaying },
      playBackStatusUpdate
    );
    setSound(newSound);
    setIsPlaying(true);
  };

  const onPlayPausePress = async () => {
    if (!sound) {
      return;
    }

    console.log(sound);
    if (isPlaying) {
      await sound.pauseAsync();
      setIsPlaying(false);
    } else {
      await sound.playAsync();
      setIsPlaying(true);
    }
  };

  if (song === null) {
    return null;
  }
}

export default PlayerWidget;

Can you tell me what I am doing wrong?

0 Answers
Related