2024-10-20 08:32:29 +00:00
|
|
|
import { useEffect, useState } from "react";
|
|
|
|
|
import { Audio } from 'expo-av';
|
|
|
|
|
import { Sound } from 'expo-av/build/Audio';
|
|
|
|
|
|
|
|
|
|
export function useAudio(soundFile: any, soundEnabled: boolean) {
|
|
|
|
|
const [sound, setSound] = useState<Sound | null>(null);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const configureAudio = async () => {
|
|
|
|
|
await Audio.setAudioModeAsync({
|
|
|
|
|
allowsRecordingIOS: false,
|
2025-04-08 19:04:33 +00:00
|
|
|
staysActiveInBackground: true,
|
2024-10-20 08:32:29 +00:00
|
|
|
playsInSilentModeIOS: true,
|
|
|
|
|
shouldDuckAndroid: true,
|
|
|
|
|
playThroughEarpieceAndroid: false,
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (soundEnabled) {
|
|
|
|
|
configureAudio();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
if (sound) {
|
|
|
|
|
sound.unloadAsync();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}, [soundEnabled]);
|
|
|
|
|
|
|
|
|
|
async function playSound() {
|
|
|
|
|
if (!soundEnabled) return;
|
|
|
|
|
|
|
|
|
|
const { sound } = await Audio.Sound.createAsync(soundFile);
|
|
|
|
|
setSound(sound);
|
|
|
|
|
|
|
|
|
|
await sound.playAsync();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
return sound
|
|
|
|
|
? () => {
|
|
|
|
|
sound.unloadAsync();
|
|
|
|
|
}
|
|
|
|
|
: undefined;
|
|
|
|
|
}, [sound]);
|
|
|
|
|
|
|
|
|
|
return { playSound };
|
|
|
|
|
}
|