Vai al contenuto

Iniziare

  1. Installa il pacchetto

    Terminal window
    npm i @capgo/native-audio
  2. Sincronizzazione con progetti nativi

    Terminal window
    npx cap sync
  3. Aggiungi file audio Inserisci i tuoi file audio nelle cartelle della piattaforma appropriata:

    • iOS: ios/App/App/sounds/
    • Android: android/app/src/main/res/raw/

Importa il plugin e precarica i file audio prima della riproduzione:

import { NativeAudio } from '@capgo/native-audio';
// Preload audio files
const 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 audio
const playSound = async () => {
await NativeAudio.play({
assetId: 'click'
});
};
// Play with options
const playMusic = async () => {
await NativeAudio.play({
assetId: 'background-music',
time: 0 // Start from beginning
});
};
// Loop audio
const loopMusic = async () => {
await NativeAudio.loop({
assetId: 'background-music'
});
};
// Stop audio
const stopMusic = async () => {
await NativeAudio.stop({
assetId: 'background-music'
});
};
// Unload when done
const cleanup = async () => {
await NativeAudio.unload({
assetId: 'click'
});
await NativeAudio.unload({
assetId: 'background-music'
});
};

Precarica un file audio per una riproduzione semplice (ideale per suoni brevi).

interface PreloadOptions {
assetId: string;
assetPath: string;
audioChannelNum?: number;
isUrl?: boolean;
}
await NativeAudio.preload({
assetId: 'sound-effect',
assetPath: 'sounds/effect.mp3',
audioChannelNum: 1,
isUrl: false
});

Precarica l’audio con opzioni avanzate (ideale per musica/audio di sottofondo).

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

Riproduce un file audio precaricato.

interface PlayOptions {
assetId: string;
time?: number; // Start time in seconds
}
await NativeAudio.play({
assetId: 'sound-effect',
time: 0
});

Esegue il loop continuo di un file audio precaricato.

await NativeAudio.loop({
assetId: 'background-music'
});

Interrompe la riproduzione di un file audio.

await NativeAudio.stop({
assetId: 'background-music'
});

Mette in pausa la riproduzione audio.

await NativeAudio.pause({
assetId: 'background-music'
});

Riprende l’audio in pausa.

await NativeAudio.resume({
assetId: 'background-music'
});

Imposta il volume per una risorsa audio.

interface SetVolumeOptions {
assetId: string;
volume: number; // 0.0 to 1.0
}
await NativeAudio.setVolume({
assetId: 'background-music',
volume: 0.3
});

Ottiene la durata di un file audio in secondi.

const { duration } = await NativeAudio.getDuration({
assetId: 'background-music'
});
console.log(`Duration: ${duration} seconds`);

Ottiene il tempo di riproduzione corrente in secondi.

const { currentTime } = await NativeAudio.getCurrentTime({
assetId: 'background-music'
});
console.log(`Current time: ${currentTime} seconds`);

Controlla se l’audio è attualmente in riproduzione.

const { isPlaying } = await NativeAudio.isPlaying({
assetId: 'background-music'
});
console.log(`Is playing: ${isPlaying}`);

Scarica un file audio dalla memoria.

await NativeAudio.unload({
assetId: 'sound-effect'
});
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();
}
}
// Load audio from URL
await NativeAudio.preloadComplex({
assetId: 'remote-audio',
assetPath: 'https://example.com/audio.mp3',
isUrl: true,
volume: 0.8
});
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 });
};
  1. Precarica durante l’inizializzazione dell’app

    import { App } from '@capacitor/app';
    App.addListener('appStateChange', async ({ isActive }) => {
    if (isActive) {
    await soundManager.init();
    }
    });
  2. Gestire gli errori con garbo

    try {
    await NativeAudio.play({ assetId: 'sound' });
    } catch (error) {
    console.log('Audio playback failed, continuing silently');
    }
  3. Scarica l’audio inutilizzato

    // Unload sounds when leaving a screen
    ionViewWillLeave() {
    this.unloadScreenSounds();
    }
  4. Utilizzare metodi di precarico appropriati

    • preload() per brevi effetti sonori (< 5 secondi)
    • preloadComplex() per musica e audio più lungo
  • Supporta AAC, MP3, WAV e altri formati Core Audio
  • Utilizza AVAudioPlayer per audio complesso
  • Utilizza i servizi audio di sistema per un audio semplice
  • Supporta l’audio di sottofondo con la corretta configurazione
  • Supporta i formati MP3, OGG, WAV
  • Utilizza SoundPool per un audio semplice
  • Utilizza MediaPlayer per audio complessi
  • Potrebbe richiedere l’autorizzazione WAKE_LOCK per la riproduzione in background

Inserisci i file in ios/App/App/sounds/ o crea un riferimento alla cartella in Xcode.

Inserisci i file in android/app/src/main/res/raw/. Nota: i nomi dei file devono essere in minuscolo e senza caratteri speciali.

  1. Audio non riprodotto

    • Assicurarsi che i file siano nelle directory corrette
    • Verifica la compatibilità del formato del file
    • Verificare che assetId corrisponda esattamente
  2. Ritardo nella riproduzione

    • Utilizza preload() per gli effetti sonori
    • Precarica prima di dover giocare
  3. Problemi di memoria

    • Scarica i file audio quando non sono necessari
    • Non precaricare troppi file di grandi dimensioni
  4. Riproduzione in sottofondo

    • Configura la funzionalità audio di sottofondo su iOS
    • Gestisci il focus audio su Android