Java

Sounds in React Native with Expo

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

1. Installation

npm install expo-av

2. File structure

Place your MP3 file in the assets/sounds folder:

assets/sounds/musica.mp3

3. Basic usage

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 ( 

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

// 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 (   			
Categories

Leave a Comment