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 ( ); }
5. Configure Audio Mode (Optional but Recommended)
Add this to the beginning of your app (e.g., in App.js) for sound to work even when the phone is on silent mode:
jsx
import { Audio } from 'expo-av'; await Audio.setAudioModeAsync({ playsInSilentModeIOS: true, // iOS: sound will play even in silent mode staysActiveInBackground: false, });
Quick Summary
| What You Need | Solution |
|---|---|
| Install | npx expo install expo-av |
| Load MP3 | Audio.Sound.createAsync(require(...)) |
| Free Memory | .unloadAsync() in the useEffect cleanup |
| Silence on iOS | setAudioModeAsync({ playsInSilentModeIOS: true }) |
