Commencer
-
Installer the package
Fenêtre de terminal npm i @capgo/native-audioFenêtre de terminal pnpm add @capgo/native-audioFenêtre de terminal yarn add @capgo/native-audioFenêtre de terminal bun add @capgo/native-audio -
Synchroniser with Natif projects
Fenêtre de terminal npx cap syncFenêtre de terminal pnpm cap syncFenêtre de terminal yarn cap syncFenêtre de terminal bunx cap sync -
Ajouter audio files Place your audio files in the appropriate platform folders:
- iOS:
ios/App/App/sounds/ - Android:
android/app/src/main/res/raw/
- iOS:
Utilisation
Section titled “Utilisation”Importer the plugin and preload audio files before playing:
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 Référence
Section titled “API Référence”preload(Options)
Section titled “preload(Options)”Preloads an audio file for simple playback (best for short sounds).
interface PreloadOptions { assetId: string; assetPath: string; audioChannelNum?: number; isUrl?: boolean;}
await NativeAudio.preload({ assetId: 'sound-effect', assetPath: 'sounds/effect.mp3', audioChannelNum: 1, isUrl: false});preloadComplex(Options)
Section titled “preloadComplex(Options)”Preloads audio with advanced Options (best for music/background audio).
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});play(Options)
Section titled “play(Options)”Plays a preloaded audio file.
interface PlayOptions { assetId: string; time?: number; // Start time in seconds}
await NativeAudio.play({ assetId: 'sound-effect', time: 0});loop(Options)
Section titled “loop(Options)”Loops a preloaded audio file continuously.
await NativeAudio.loop({ assetId: 'background-music'});Arrêter(Options)
Section titled “Arrêter(Options)”Stops playing an audio file.
await NativeAudio.stop({ assetId: 'background-music'});pause(Options)
Section titled “pause(Options)”Pauses audio playback.
await NativeAudio.pause({ assetId: 'background-music'});resume(Options)
Section titled “resume(Options)”Resumes paused audio.
await NativeAudio.resume({ assetId: 'background-music'});setVolume(Options)
Section titled “setVolume(Options)”Sets the volume for an audio asset.
interface SetVolumeOptions { assetId: string; volume: number; // 0.0 to 1.0}
await NativeAudio.setVolume({ assetId: 'background-music', volume: 0.3});getDuration(Options)
Section titled “getDuration(Options)”Gets the duration of an audio file in seconds.
const { duration } = await NativeAudio.getDuration({ assetId: 'background-music'});console.log(`Duration: ${duration} seconds`);getCurrentTime(Options)
Section titled “getCurrentTime(Options)”Gets the current playback time in seconds.
const { currentTime } = await NativeAudio.getCurrentTime({ assetId: 'background-music'});console.log(`Current time: ${currentTime} seconds`);isPlaying(Options)
Section titled “isPlaying(Options)”Checks if audio is currently playing.
const { isPlaying } = await NativeAudio.isPlaying({ assetId: 'background-music'});console.log(`Is playing: ${isPlaying}`);unload(Options)
Section titled “unload(Options)”Unloads an audio file from memory.
await NativeAudio.unload({ assetId: 'sound-effect'});Advanced Utilisation
Section titled “Advanced Utilisation”Sound Manager Class
Section titled “Sound Manager Class”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(); }}Loading from URLs
Section titled “Loading from URLs”// Load audio from URLawait NativeAudio.preloadComplex({ assetId: 'remote-audio', assetPath: 'https://example.com/audio.mp3', isUrl: true, volume: 0.8});Fade In/Out Effects
Section titled “Fade In/Out Effects”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 });};Best Practices
Section titled “Best Practices”-
Preload during Application Initialisation
import { App } from '@capacitor/app';App.addListener('appStateChange', async ({ isActive }) => {if (isActive) {await soundManager.init();}}); -
Handle errors gracefully
try {await NativeAudio.play({ assetId: 'sound' });} catch (error) {console.log('Audio playback failed, continuing silently');} -
Unload unused audio
// Unload sounds when leaving a screenionViewWillLeave() {this.unloadScreenSounds();} -
Use appropriate preload methods
preload()for short sound effects (< 5 seconds)preloadComplex()for music and longer audio
Platform Notes
Section titled “Platform Notes”- Supports AAC, MP3, WAV, and other Core Audio formats
- Uses AVAudioPlayer for complex audio
- Uses System Sound Services for simple audio
- Supports background audio with proper Configuration
Android
Section titled “Android”- Supports MP3, OGG, WAV formats
- Uses SoundPool for simple audio
- Uses MediaPlayer for complex audio
- May require WAKE_LOCK permission for background playback
File Placement
Section titled “File Placement”Place files in ios/App/App/sounds/ or create a folder reference in Xcode.
Android
Section titled “Android”Place files in android/app/src/main/res/raw/.
Remarque: File names must be lowercase with no special characters.
Problèmes courants
Section titled “Problèmes courants”-
Audio not playing
- Ensure files are in correct directories
- Vérifier file format compatibility
- Verify assetId matches exactly
-
Delay in playback
- Use
preload()for sound effects - Preload before you need to play
- Use
-
Memory issues
- Unload audio files when not needed
- Don’t preload too many large files
-
Background playback
- Configure background audio capability on iOS
- Handle audio focus on Android