Я использую 50 различных звуковых файлов. он работает нормально, но с 14-й или 15-й попытки он больше не воспроизводит аудиофайлы. (Я использую устройство Android)
const animalSound = new Sound( selectedAnimals.soundUrl ||"snake.mp3", null, error => {
if (error) console.info("Can't play sound. ", error);
})
const handlePlaySound = () => {
animalSound.setVolume(1);
animalSound.play(() => {
animalSound.release();
});
};
const handleStopSound = id => {
animalSound.stop()
}
Я использовал expo-av
для звука, который также можно использовать в голом реактивно-нативном проекте. (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"));
Я добавил функцию остановки звука, скажите, работает ли она сейчас
Все функции работают без проблем. Спасибо, что уделили мне время.
Благодарю вас! Я перевел свое приложение на выставку и успешно работаю над ним. Но когда я хочу остановить звук, как я могу это сделать?