Empezando
-
Instalar el paquete
Ventana de terminal npm i @capgo/native-audioVentana de terminal pnpm add @capgo/native-audioVentana de terminal yarn add @capgo/native-audioVentana de terminal bun add @capgo/native-audio -
Sincronización con proyectos nativos
Ventana de terminal npx cap syncVentana de terminal pnpm cap syncVentana de terminal yarn cap syncVentana de terminal bunx cap sync -
Agregar archivos de audio Coloque sus archivos de audio en las carpetas de la plataforma apropiadas:
- iOS:
ios/App/App/sounds/ - Android:
android/app/src/main/res/raw/
- iOS:
Importe el complemento y precargue los archivos de audio antes de reproducirlos:
import { NativeAudio } from '@capgo/native-audio';
// Preload audio filesconst preloadAudio = async () => { // Simple preload for short sounds await NativeAudio.preload({ assetId: 'click', assetPath: 'sounds/click.mp3', audioChannelNum: 1, isUrl: false });
// Complex preload for music/longer audio await NativeAudio.preloadComplex({ assetId: 'background-music', assetPath: 'sounds/background.mp3', audioChannelNum: 1, volume: 0.5, delay: 0, isUrl: false });};
// Play audioconst playSound = async () => { await NativeAudio.play({ assetId: 'click' });};
// Play with optionsconst playMusic = async () => { await NativeAudio.play({ assetId: 'background-music', time: 0 // Start from beginning });};
// Loop audioconst loopMusic = async () => { await NativeAudio.loop({ assetId: 'background-music' });};
// Stop audioconst stopMusic = async () => { await NativeAudio.stop({ assetId: 'background-music' });};
// Unload when doneconst cleanup = async () => { await NativeAudio.unload({ assetId: 'click' }); await NativeAudio.unload({ assetId: 'background-music' });};API Referencia
Section titled “API Referencia”precarga (opciones)
Section titled “precarga (opciones)”Precarga un archivo de audio para una reproducción sencilla (mejor para sonidos cortos).
interface PreloadOptions { assetId: string; assetPath: string; audioChannelNum?: number; isUrl?: boolean;}
await NativeAudio.preload({ assetId: 'sound-effect', assetPath: 'sounds/effect.mp3', audioChannelNum: 1, isUrl: false});precargaComplejo(opciones)
Section titled “precargaComplejo(opciones)”Precarga audio con opciones avanzadas (mejor para música/audio de fondo).
interface PreloadComplexOptions { assetId: string; assetPath: string; volume?: number; // 0.0 to 1.0 audioChannelNum?: number; delay?: number; isUrl?: boolean; fadeDuration?: number;}
await NativeAudio.preloadComplex({ assetId: 'theme-song', assetPath: 'sounds/theme.mp3', volume: 0.7, audioChannelNum: 2, isUrl: false});jugar(opciones)
Section titled “jugar(opciones)”Reproduce un archivo de audio precargado.
interface PlayOptions { assetId: string; time?: number; // Start time in seconds}
await NativeAudio.play({ assetId: 'sound-effect', time: 0});bucle (opciones)
Section titled “bucle (opciones)”Realiza un bucle continuo de un archivo de audio precargado.
await NativeAudio.loop({ assetId: 'background-music'});detener(opciones)
Section titled “detener(opciones)”Deja de reproducir un archivo de audio.
await NativeAudio.stop({ assetId: 'background-music'});pausa (opciones)
Section titled “pausa (opciones)”Pausa la reproducción de audio.
await NativeAudio.pause({ assetId: 'background-music'});currículum (opciones)
Section titled “currículum (opciones)”Reanuda el audio en pausa.
await NativeAudio.resume({ assetId: 'background-music'});establecerVolumen(opciones)
Section titled “establecerVolumen(opciones)”Establece el volumen de un recurso de audio.
interface SetVolumeOptions { assetId: string; volume: number; // 0.0 to 1.0}
await NativeAudio.setVolume({ assetId: 'background-music', volume: 0.3});obtenerDuración(opciones)
Section titled “obtenerDuración(opciones)”Obtiene la duración de un archivo de audio en segundos.
const { duration } = await NativeAudio.getDuration({ assetId: 'background-music'});console.log(`Duration: ${duration} seconds`);getCurrentTime(opciones)
Section titled “getCurrentTime(opciones)”Obtiene el tiempo de reproducción actual en segundos.
const { currentTime } = await NativeAudio.getCurrentTime({ assetId: 'background-music'});console.log(`Current time: ${currentTime} seconds`);está reproduciendo (opciones)
Section titled “está reproduciendo (opciones)”Comprueba si el audio se está reproduciendo actualmente.
const { isPlaying } = await NativeAudio.isPlaying({ assetId: 'background-music'});console.log(`Is playing: ${isPlaying}`);descargar (opciones)
Section titled “descargar (opciones)”Descarga un archivo de audio de la memoria.
await NativeAudio.unload({ assetId: 'sound-effect'});Uso avanzado
Section titled “Uso avanzado”Clase de administrador de sonido
Section titled “Clase de administrador de sonido”import { NativeAudio } from '@capgo/native-audio';
export class SoundManager { private sounds: Map<string, boolean> = new Map(); private volume = 1.0;
async init() { // Preload all sounds await this.preloadSound('click', 'sounds/click.mp3'); await this.preloadSound('success', 'sounds/success.mp3'); await this.preloadSound('error', 'sounds/error.mp3');
// Preload music await this.preloadMusic('background', 'sounds/background.mp3', 0.5); }
private async preloadSound(id: string, path: string) { try { await NativeAudio.preload({ assetId: id, assetPath: path, audioChannelNum: 1, isUrl: false }); this.sounds.set(id, true); } catch (error) { console.error(`Failed to preload ${id}:`, error); } }
private async preloadMusic(id: string, path: string, volume: number) { try { await NativeAudio.preloadComplex({ assetId: id, assetPath: path, volume, audioChannelNum: 2, isUrl: false }); this.sounds.set(id, true); } catch (error) { console.error(`Failed to preload ${id}:`, error); } }
async playSound(id: string) { if (!this.sounds.has(id)) { console.warn(`Sound ${id} not preloaded`); return; }
try { await NativeAudio.play({ assetId: id }); } catch (error) { console.error(`Failed to play ${id}:`, error); } }
async playMusic(id: string) { if (!this.sounds.has(id)) return;
try { await NativeAudio.loop({ assetId: id }); } catch (error) { console.error(`Failed to play music ${id}:`, error); } }
async stopMusic(id: string) { try { await NativeAudio.stop({ assetId: id }); } catch (error) { console.error(`Failed to stop ${id}:`, error); } }
async setMasterVolume(volume: number) { this.volume = Math.max(0, Math.min(1, volume));
// Update all loaded sounds for (const [id] of this.sounds) { await NativeAudio.setVolume({ assetId: id, volume: this.volume }); } }
async cleanup() { for (const [id] of this.sounds) { await NativeAudio.unload({ assetId: id }); } this.sounds.clear(); }}Cargando desde URL
Section titled “Cargando desde URL”// Load audio from URLawait NativeAudio.preloadComplex({ assetId: 'remote-audio', assetPath: 'https://example.com/audio.mp3', isUrl: true, volume: 0.8});Efectos de aparición y desaparición gradual
Section titled “Efectos de aparición y desaparición gradual”const fadeIn = async (assetId: string, duration: number) => { const steps = 20; const stepDuration = duration / steps;
await NativeAudio.setVolume({ assetId, volume: 0 }); await NativeAudio.play({ assetId });
for (let i = 1; i <= steps; i++) { await new Promise(resolve => setTimeout(resolve, stepDuration)); await NativeAudio.setVolume({ assetId, volume: i / steps }); }};
const fadeOut = async (assetId: string, duration: number) => { const steps = 20; const stepDuration = duration / steps;
for (let i = steps; i >= 0; i--) { await NativeAudio.setVolume({ assetId, volume: i / steps }); await new Promise(resolve => setTimeout(resolve, stepDuration)); }
await NativeAudio.stop({ assetId });};Mejores prácticas
Section titled “Mejores prácticas”-
Precarga durante la inicialización de la aplicación
import { App } from '@capacitor/app';App.addListener('appStateChange', async ({ isActive }) => {if (isActive) {await soundManager.init();}}); -
Maneja los errores con elegancia
try {await NativeAudio.play({ assetId: 'sound' });} catch (error) {console.log('Audio playback failed, continuing silently');} -
Descargar audio no utilizado
// Unload sounds when leaving a screenionViewWillLeave() {this.unloadScreenSounds();} -
Utilice métodos de precarga adecuados
preload()para efectos de sonido cortos (< 5 segundos)preloadComplex()para música y audio más largo
Notas de plataforma
Section titled “Notas de plataforma”- Admite AAC, MP3, WAV y otros formatos Core Audio
- Utiliza AVAudioPlayer para audio complejo
- Utiliza System Sound Services para audio simple
- Admite audio de fondo con la configuración adecuada
Android
Section titled “Android”- Soporta formatos MP3, OGG, WAV
- Utiliza SoundPool para audio simple
- Utiliza MediaPlayer para audio complejo
- Puede requerir permiso WAKE_LOCK para reproducción en segundo plano
Colocación de archivos
Section titled “Colocación de archivos”Coloque archivos en ios/App/App/sounds/ o cree una referencia de carpeta en Xcode.
Android
Section titled “Android”Coloque archivos en android/app/src/main/res/raw/.
Nota: Los nombres de los archivos deben estar en minúsculas y sin caracteres especiales.
Problemas comunes
Section titled “Problemas comunes”-
El audio no se reproduce
- Asegúrese de que los archivos estén en los directorios correctos.
- Verificar la compatibilidad del formato de archivo
- Verificar que el identificador de activo coincida exactamente
-
Retraso en la reproducción
- Utilice
preload()para efectos de sonido - Precarga antes de que necesites jugar
- Utilice
-
Problemas de memoria
- Descargar archivos de audio cuando no sea necesario
- No precargues demasiados archivos grandes
-
Reproducción en segundo plano
- Configurar la capacidad de audio de fondo en iOS
- Manejar el enfoque de audio en Android