一段时间后反应本机声音不起作用

react-native sound not working after a while

我使用了 50 个不同的声音文件。它工作正常,但在我第 14 次或第 15 次尝试时,它不再播放音频文件。 (我正在使用 android 设备)

  const animalSound = new Sound( selectedAnimals.soundUrl ||"snake.mp3", null, error => {
    if (error) console.log("Can't play sound. ", error);
  })

const handlePlaySound = () => {
    animalSound.setVolume(1);
    animalSound.play(() => {
        animalSound.release();
    });
  };

const handleStopSound = id => {
    animalSound.stop()
}

我用 expo-av 做声音,它也可以用在裸 react-native 项目中。 (https://github.com/expo/expo/tree/main/packages/expo-av)

我制作了这个钩子,它可以让你播放声音,还可以为你清理资源,这样你就不用担心了。

/* 
    This hooks abstracts away all the logic of 
    loading up and unloading songs. All the hook 
    takes in is the require path of the audio
*/
import React,{useState,useEffect} from 'react'
import { Audio } from 'expo-av';

const useSound = (path) => {
  /* 
    Sound state
  */
  const [sound, setSound] = useState();

  /* 
    Logic to unload sound when screen changes
  */
  useEffect(() => {
    return sound
        ? () => {
            sound.unloadAsync();
        }
        : undefined;
  }, [sound]);
 
  /*
    Memoize the function so that it does not get 
    recomputed every time that the screen load
  */
  const playSound = React.useCallback(async ()=>{
      const { sound } = await Audio.Sound.createAsync(path);
      setSound(sound);
      await sound.playAsync();
  },[sound])

   
  /* 
     Stop sound 
  */
  const stopSound = React.useCallback(async ()=>{
      await sound.stopAsync();
  },[sound])

  return [playSound,stopSound]
}

要使用声音,您只需要这样做

/* 
    The hooks returns a function to be called when to play 
    a sound, and it abstracts away having to deal with unloading'
    the sound
 */
const [playSound,stopSound] = useSound(require("snake.mp3"));