0

我在安卓设备上运行我的应用程序。所以我使用 Context API,歌曲在上下文中,每当用户点击歌曲时,它都会在上下文中更新,每个组件都会获取它,然后触发 PlayerWidget 的 useEffect ,那时我的应用程序崩溃了。在应用程序开始时,歌曲为空。

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;

你能告诉我我做错了什么吗?

4

0 回答 0