Native Audio for Capacitor

repository·master·Indexed 41 days ago

https://github.com/capacitor-community/native-audio

A native plugin for Capacitor (version 8.0.0) that provides optimized audio playback on Android, iOS, and Web by preloading assets into memory. It includes a comprehensive API for preloading, playing, pausing, resuming, stopping, and looping audio, as well as volume control and state tracking via methods like isPlaying(), getDuration(), and getCurrentTime().

Tokens
3.5K
Snippets
18
Records
22
Agent score
99%

What's inside Native Audio

  1. Install @capacitor-community/native-audio

    master

    To use the Native Audio plugin, install the package via npm or yarn and then sync your native projects.

    # Using npm
    npm install @capacitor-community/native-audio
    
    # Using yarn
    yarn add @capacitor-community/native-audio
    
    # Sync native files
    npx cap sync
  2. Listen for the 'complete' event

    master

    You can listen for the complete event to know when an audio asset has finished playing.

    Note: This feature is available since version 5.0.1.

    import { NativeAudio } from '@capacitor-community/native-audio';
    
    const listener = await NativeAudio.addListener('complete', (event) => {
      console.log(`Asset ${event.assetId} finished playing`);
    });
    
    // To stop listening later:
    // await listener.remove();
  3. Get audio state and metadata

    master

    Retrieve information about the current playback state or file properties:

    • isPlaying({ assetId }): Returns a promise resolving to { isPlaying: boolean }. Returns false if the audio is paused or not loaded.
    • getDuration({ assetId }): Returns a promise resolving to { duration: number }. Note: Only works if audioChannelNum is 1.
    • getCurrentTime({ assetId }): Returns a promise resolving to { currentTime: number }. Note: Only works if audioChannelNum is 1.
    import { NativeAudio } from '@capacitor-community/native-audio';
    
    // Check if playing
    const { isPlaying } = await NativeAudio.isPlaying({ assetId: 'fire' });
    
    // Get duration
    const { duration } = await NativeAudio.getDuration({ assetId: 'fire' });
    
    // Get current playback time
    const { currentTime } = await NativeAudio.getCurrentTime({ assetId: 'fire' });
  4. Manage audio volume and memory

    master

    Use these methods to adjust audio properties or free up resources:

    • setVolume({ assetId, volume }): Sets the volume for a specific asset. The volume value should be between 0.1 and 1.0.
    • unload({ assetId }): Unloads the audio file from memory to free up resources.
    import { NativeAudio } from '@capacitor-community/native-audio';
    
    // Set volume to 40%
    await NativeAudio.setVolume({
      assetId: 'fire',
      volume: 0.4,
    });
    
    // Unload from memory
    await NativeAudio.unload({ assetId: 'fire' });
  5. Preload audio assets with preload()

    master

    Use NativeAudio.preload() to load audio files into memory for optimized playback. This is a required step before playing an asset.

    Parameters:

    • assetId: A unique identifier for the file.
    • assetPath: The relative path to the file (within the platform folders) or an absolute URL (file://).
    • audioChannelNum: Number of audio channels.
    • isUrl: Set to true if assetPath is a file:// URL.
    • volume: (Optional) Initial volume level.
    import { NativeAudio } from '@capacitor-community/native-audio';
    
    await NativeAudio.preload({
        assetId: "fire",
        assetPath: "fire.mp3",
        audioChannelNum: 1,
        isUrl: false
    });
  6. Configure audio behavior with configure()

    master

    The configure() method allows you to set global audio behaviors. This method is supported on Android and iOS but not on Web.

    Options:

    • fade (boolean): Whether or not to fade audio. Defaults to false.
    • focus (boolean): Whether or not to disable mixed audio. Defaults to false.
    import { NativeAudio } from '@capacitor-community/native-audio';
    
    await NativeAudio.configure({
      fade: true,
      focus: true
    });
  7. Play, pause, and control audio playback

    master

    Once an asset is preloaded, you can control its playback using the following methods:

    • play({ assetId, time }): Plays the loaded audio. The time parameter is optional and allows you to seek to a specific second (e.g., 6.0).
    • pause({ assetId }): Pauses the audio.
    • resume({ assetId }): Resumes a paused audio.
    • stop({ assetId }): Stops the audio playback.
    • loop({ assetId }): Sets the audio to loop continuously.
    import { NativeAudio } from '@capacitor-community/native-audio';
    
    // Play from the beginning
    await NativeAudio.play({ assetId: 'fire' });
    
    // Play and seek to 6 seconds
    await NativeAudio.play({ assetId: 'fire', time: 6.0 });
    
    // Loop the audio
    await NativeAudio.loop({ assetId: 'fire' });
    
    // Stop playback
    await NativeAudio.stop({ assetId: 'fire' });
  8. Configure the Capacitor app identity and web directory

    master

    The capacitor.config.ts file defines the core identity of the Capacitor application. For the native-audio example app, the following configuration is used:

    • appId: The unique identifier for the application (e.g., ryltsov.alex.nativeaudio.demo).
    • appName: The display name of the application (e.g., example-app).
    • webDir: The directory containing the web assets (e.g., www/browser).
    import type { CapacitorConfig } from '@capacitor/cli';
    
    const config: CapacitorConfig = {
      appId: 'ryltsov.alex.nativeaudio.demo',
      appName: 'example-app',
      webDir: 'www/browser'
    };
    
    export default config;
  9. Configure the example-app Ionic project

    master

    The ionic.config.json file defines the project name, integration types, and framework structure for the example-app. In this project, it specifies that the app uses the capacitor integration and follows the angular-standalone project type.

    {
      "name": "example-app",
      "integrations": {
        "capacitor": {}
      },
      "type": "angular-standalone"
    }
  10. Control audio playback

    master

    The NativeAudio interface provides several methods to control the playback of preloaded assets using their assetId.

    // Play an asset, optionally starting at a specific time
    await NativeAudio.play({ assetId: 'explosion', time: 0 });
    
    // Pause playback
    await NativeAudio.pause({ assetId: 'explosion' });
    
    // Resume paused playback
    await NativeAudio.resume({ assetId: 'explosion' });
    
    // Set the asset to loop
    await NativeAudio.loop({ assetId: 'explosion' });
    
    // Stop playback
    await NativeAudio.stop({ assetId: 'explosion' });
    
    // Unload the asset from memory
    await NativeAudio.unload({ assetId: 'explosion' });