Sonidos en React Native con Expo

Tiempo de lectura: 2 minutos

La forma más sencilla con Expo es usar expo-av. Te explico paso a paso:

1. Instalación

bash

npx expo install expo-av

2. Estructura de archivos

Coloca tu MP3 en la carpeta assets:

assets/
  sounds/
    musica.mp3

3. Uso básico

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();
  };

  // Importante: liberar memoria al desmontar
  useEffect(() => {
    return () => {
      soundRef.current?.unloadAsync();
    };
  }, []);

  return (
    <Button title="Reproducir" onPress={playSound} />
  );
}

4. Hook reutilizable (recomendado)

Si lo vas a usar en varios sitios, mejor un 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 (
    <>
      <Button title="▶ Play" onPress={play} />
      <Button title="⏹ Stop" onPress={stop} />
    </>
  );
}

5. Configurar modo de audio (opcional pero recomendado)

Agrega esto una vez al inicio de tu app (ej. en App.js) para que el sonido funcione aunque el teléfono esté en silencio:

jsx

import { Audio } from 'expo-av';

await Audio.setAudioModeAsync({
  playsInSilentModeIOS: true,   // iOS: suena aunque esté en silencio
  staysActiveInBackground: false,
});

Resumen rápido

Qué necesitasSolución
Instalarnpx expo install expo-av
Cargar MP3Audio.Sound.createAsync(require(...))
Liberar memoria.unloadAsync() en el useEffect cleanup
Silencio en iOSsetAudioModeAsync({ playsInSilentModeIOS: true })

Deja un comentario