boxons/components/useCases/timer/business/useAudio.ts

49 lines
1.0 KiB
TypeScript

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,
staysActiveInBackground: false,
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 };
}