Sounds in React Native with Expo

Tiempo de lectura: < 1 minuto

The simplest way with Expo is to use expo-av. I’ll explain it step by step:

bash

npm install expo-av

2. File structure

Place your MP3 file in the assets/sounds folder:

assets/sounds/musica.mp3

3. Basic usage

jsx

import { useEffect, useRef } from 'react'; import { Audio } from 'expo-av'; export default function MiComponente() { const soundRef = useRef(null); const playSound = async () => { const { sound } = await Audio.Sound.createAsync( require('./assets/sounds/musica.mp3') ); soundRef.current = sound; await sound.playAsync(); }; // Important: free up memory when unmounting useEffect(() => { return () => { soundRef.current?.unloadAsync(); }; }, []); return ( 

4. Reusable hook (recommended)

If you’re going to use it in multiple places, better a hook:

// hooks/useSound.js import { useEffect, useRef, useCallback } from 'react'; import { Audio } from 'expo-av'; export function useSound(source) { const soundRef = useRef(null); const play = useCallback(async () => { // Si ya hay un sonido cargado, descárgalo primero if (soundRef.current) { await soundRef.current.unloadAsync(); } const { sound } = await Audio.Sound.createAsync(source); soundRef.current = sound; await sound.playAsync(); }, [source]); const stop = useCallback(async () => { await soundRef.current?.stopAsync(); }, []); useEffect(() => { return () => { soundRef.current?.unloadAsync(); }; }, []); return { play, stop };
// Uso en cualquier componente import { useSound } from './hooks/useSound'; export default function Creditos() { const { play, stop } = useSound( require('./assets/sounds/musica.mp3') ); return (   			

Leave a Comment