Commit c888f4c3 authored by Lorenzo Trujillo Rojas's avatar Lorenzo Trujillo Rojas
Browse files

Se creó un hook para reproducir un audio

parent a69581be
Loading
Loading
Loading
Loading
+44 −0
Original line number Diff line number Diff line
import { AVPlaybackSource, AVPlaybackStatus, Audio } from "expo-av";
import { useEffect, useState } from "react";

interface AudioPlayerProps {
    source: AVPlaybackSource;
}

export const useAudio = ({ source }: AudioPlayerProps) => {
    const [sound, setSound] = useState<Audio.Sound | null>(null);
    const [isPlaying, setIsPlaying] = useState(false);

    const loadAudio = async () => {
        const { sound, status } = await Audio.Sound.createAsync(source, {
            shouldPlay: false
        });
        if (status.isLoaded) {
            setSound(sound);
            setIsPlaying(status.isPlaying);
        }
    }

    const togglePlay = async () => {
        if (sound) {
            if (isPlaying) {
                await sound.pauseAsync();
            } else {
                await sound.playAsync();
            }
            setIsPlaying(!isPlaying);
        }
    }

    useEffect(() => {
        loadAudio();
        return () => {
            if (sound) {
                sound.pauseAsync();
                sound.unloadAsync();
            }
        }
    }, [source]);

    return { togglePlay, isPlaying };
}
 No newline at end of file