Skip to content
Proyek

Cap-go/capacitor-native-audio

Lihat di GitHub

Tentang

Capacitor plugin for native audio engine.

Desain dan media

Cara angka ini diukur

Yang dapat Anda lakukan

  • Preload and play: preload(), play(), playOnce(), pause(), resume(), loop() and stop().
  • Playlist queue: setQueue(), queueNext(), queuePrevious(), queueSelect(), getQueueState() with lock screen skip on iOS and Android.
  • Sources: local files, file:// paths, remote https:// URLs and M3U8 HLS streams.
  • Controls: setVolume(), setRate() (0.25x to 4x), setCurrentTime(), getPlaybackState(), getRate().

Pertumbuhan bintang terukur

dalam 24 jam
0
dalam 7 hari
0
dalam 15 hari
0
dalam 1 bulan
Mengumpulkan riwayat

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

Native audio

Play sound effects, music and streams with native audio engines in your Capacitor app: low latency playback, background audio, lock screen controls and HLS streams on iOS and Android.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-native-audio in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-native-audio to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-native-audio for Capacitor apps

Built and maintained with AI

We build, improve and fix our plugins with heavy use of AI, so issues usually get fixed in under a day and pull requests get feedback the same day. A human still reviews, tests and merges 50+ pull requests daily.

  • Most plugin issues get a fix pull request the same day, often within a couple of hours, and are usually resolved in one to two days.
  • Every pull request goes through our AI review system, usually within minutes.
  • Our AI pre-checks tests, code review, conventions and security, then a human reviews, tests and merges.
  • A human, Martin, reviews, tests and merges 50+ pull requests every day.
  • In the last 90 days, 95% of plugin issues were resolved.

Learn more about how we build with AI

Why pick Native Audio?

@capgo/capacitor-native-audio is the free, native Capacitor 9 audio stack for sound effects, music, podcasts, and guided audio in one plugin. Keep your existing preload / play workflow and add lock screen playback, queues, and UI sync without switching packages.

Full reference: capgo.app/docs/plugins/native-audio/

Playlist queue with lock screen skip

setQueue(), queueNext(), queuePrevious(), and queueSelect() drive multi-track sessions. iOS and Android wire skip actions to the lock screen and media notification. See queue docs and repo docs/PLAYLIST.md.

Playback snapshot

getPlaybackState() returns asset id, play/pause/stop, position, and duration when a screen mounts after playback already started. Pairs with playbackState events from transport and lock screen controls.

Progress events

configure({ progressInterval }) sets how often progress fires for scrubbers and chapters. currentTime still updates about every 100ms for precise UI.

Audio routing

setSpeaker(), setEarpiece(), and getAudioRoute() on iOS and Android for voice-heavy apps. audioRouteChange fires when those APIs change routing (not when headphones or Bluetooth connect on their own). On Android it tracks speakerphone mode from setSpeaker() / setEarpiece().

Key features

  • Preload and play: preload(), play(), playOnce(), pause(), resume(), loop() and stop().
  • Playlist queue: setQueue(), queueNext(), queuePrevious(), queueSelect(), getQueueState() with lock screen skip on iOS and Android.
  • Sources: local files, file:// paths, remote https:// URLs and M3U8 HLS streams.
  • Controls: setVolume(), setRate() (0.25x to 4x), setCurrentTime(), getPlaybackState(), getRate().
  • Background and focus: configure() sets audio focus, background playback, progress interval, and Now Playing controls on iOS and Android.
  • Events: complete, currentTime, progress, playbackState, queueChange, and audioRouteChange (native routing).
  • Routing: setSpeaker() and setEarpiece() on iOS and Android for voice-style apps.
  • Platforms: iOS (AVFoundation), Android (Media3 ExoPlayer), and Web (HTMLAudio plus Media Session for queues).

Native Audio

@capgo/capacitor-native-audio

Capacitor plugin for playing sounds.

Maintenance status badge CI status badge NPM license badge
NPM weekly downloads badge NPM version badge All contributors badge

Capacitor Native Audio Plugin

Capacitor plugin for native audio engine. Capacitor V8 - ✅ Support!

Support local file, remote URL, and m3u8 stream

Click on video to see example 💥

YouTube Example

Why Native Audio?

Pick @capgo/capacitor-native-audio when you need one free, native audio stack for Capacitor 9: sound effects, long-form music, podcasts, and guided audio in the same plugin. You keep your existing preload/play flow, and you can add queues, lock screen controls, and UI sync helpers without switching plugins.

New in 8.5: playlist and UI sync

  • Queue API for multi-track sessions with queueChange events and notification skip controls.
  • getPlaybackState() snapshots for screens that mount after playback already started.
  • progress events on a configurable interval for scrubbers and chapter markers.
  • Speaker and earpiece routing on native platforms for voice-heavy apps.

The only free, full-featured audio playback plugin for Capacitor:

  • HLS/M3U8 streaming - Play live audio streams and adaptive bitrate content
  • Remote URLs - Stream from HTTP/HTTPS sources with built-in caching
  • Low-latency playback - Optimized native audio engine for sound effects and music
  • Full control - Play, pause, resume, loop, seek, volume, playback rate
  • Multiple channels - Play multiple audio files simultaneously
  • Background playback - Continue playing when app is backgrounded
  • Notification center display - Show audio metadata in iOS Control Center and Android notifications
  • Position tracking - Real-time currentTime events (100ms intervals)
  • Modern package management - Supports both Swift Package Manager (SPM) and CocoaPods (SPM-ready for Capacitor 9)
  • Same JavaScript API - Compatible interface with paid alternatives
  • Support player notification center - Play, pause, show cover for your user when long playing audio.

Perfect for music players, podcast apps, games, meditation apps, and any audio-heavy application.

Maintainers

Maintainer GitHub Social
Martin Donadieu riderx Telegram

Mainteinance Status: Actively Maintained

Preparation

All audio files must be with the rest of your source files.

First make your sound file end up in your built code folder, example in folder BUILDFOLDER/assets/sounds/FILENAME.mp3 Then use it in preload like that assets/sounds/FILENAME.mp3

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/native-audio/

Compatibility

Plugin version Capacitor compatibility Maintained
v9.*.* v9.*.* ✅
v8.*.* v8.*.* On demand
v7.*.* v7.*.* On demand
v6.*.* v6.*.* ❌
v5.*.* v5.*.* ❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v9 for Capacitor 9). Only the latest major version is actively maintained.

Migrating from v8 to v9

v9 of @capgo/capacitor-native-audio targets Capacitor 9. Update Capacitor and this plugin together, then sync the native projects:

npm install @capacitor/core@^9.0.0 @capacitor/cli@^9.0.0 @capacitor/ios@^9.0.0 @capacitor/android@^9.0.0 @capgo/capacitor-native-audio@^9.0.0
npx cap sync

Capacitor 9 needs Node.js 24+, iOS 16+ (Xcode 27) and Android minSdk 26 / compileSdk 37. Follow the official Capacitor 9 update guide for the app side changes.

No plugin API was removed: the JavaScript API of v9 is the same as v8.

Installation

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-native-audio` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

To use npm

npm install @capgo/capacitor-native-audio

To use yarn

yarn add @capgo/capacitor-native-audio

Sync native files

npx cap sync

On iOS, Android and Web, no further steps are needed.

Swift Package Manager

You can also consume the iOS implementation via Swift Package Manager. In Xcode open File → Add Package…, point it at https://github.com/Cap-go/capacitor-native-audio.git, and select the CapgoCapacitorNativeAudio library product. The package supports iOS 16 and newer alongside Capacitor 9.

Configuration

Optional HLS/m3u8 Streaming (Android)

By default, HLS streaming support is enabled for backward compatibility. However, it adds approximately 4MB to your Android APK size due to the media3-exoplayer-hls dependency.

If you don't need HLS/m3u8 streaming support, you can disable it to reduce your APK size:

// capacitor.config.ts
import type { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'My App',
  plugins: {
    NativeAudio: {
      hls: false  // Disable HLS to reduce APK size by ~4MB
    }
  }
};

export default config;

After changing the configuration, run:

npx cap sync

Notes:

  • iOS uses native AVPlayer for HLS, so this setting only affects Android
  • If HLS is disabled and you try to play an .m3u8 file, you'll get a clear error message explaining how to enable it
  • The default is hls: true to maintain backward compatibility

Notification icons (Android)

The media notification uses the system media icons. To match your app, add white-on-transparent drawables under android/app/src/main/res/drawable/ and name them in capacitor.config.ts:

const config: CapacitorConfig = {
  plugins: {
    NativeAudio: {
      smallIcon: 'ic_notification',
      seekBackwardIcon: 'ic_seek_backward',
      seekForwardIcon: 'ic_seek_forward',
    },
  },
};

The value is the drawable resource name, without @drawable/ or a file extension. If a name is missing or the resource does not exist, the plugin keeps the default icon. iOS draws the lock screen and Control Center controls itself.

Supported methods

Name Android iOS Web
configure ✅ ✅ partial (progressInterval only)
preload ✅ ✅ ✅
play ✅ ✅ ✅
pause ✅ ✅ ✅
resume ✅ ✅ ✅
loop ✅ ✅ ✅
stop ✅ ✅ ✅
unload ✅ ✅ ✅
setVolume ✅ ✅ ✅
getDuration ✅ ✅ ✅
setCurrentTime ✅ ✅ ✅
getCurrentTime ✅ ✅ ✅
isPlaying ✅ ✅ ✅
setQueue ✅ ✅ ✅
queueNext ✅ ✅ ✅
queuePrevious ✅ ✅ ✅
queueSelect ✅ ✅ ✅
queueAdd ✅ ✅ ✅
queueRemove ✅ ✅ ✅
setRepeatMode ✅ ✅ ✅
getQueueState ✅ ✅ ✅
clearQueue ✅ ✅ ✅
getPlaybackState ✅ ✅ ✅
getRate ✅ ✅ ✅
setSpeaker ✅ ✅ emits audioRouteChange
setEarpiece ✅ ✅ emits audioRouteChange
getAudioRoute ✅ ✅ last requested route

See docs/MIGRATION.md for migration notes and docs/PLAYLIST.md for a queue example.

Usage

Example repository

Notification Center Display (iOS & Android)

You can display audio playback information in the system notification center. This is perfect for music players, podcast apps, and any app that plays audio in the background.

⚠️ Important iOS Behavior

Enabling showNotification: true changes how your app's audio interacts with other apps on iOS:

  • With notifications enabled (showNotification: true): Your audio will interrupt other apps' audio (like Spotify, Apple Music, etc.). This is required for Now Playing controls to appear in Control Center and on the lock screen.
  • With notifications disabled (showNotification: false): Your audio will mix with other apps' audio, allowing background music to continue playing.

When to use each:

  • ✅ Use showNotification: true for: Music players, podcast apps, audiobook players (primary audio source)
  • ❌ Use showNotification: false for: Sound effects, notification sounds, secondary audio where mixing is preferred

See Issue #202 for technical details.

Step 1: Configure the plugin with notification support

import { NativeAudio } from '@capgo/capacitor-native-audio'

// Enable notification center display
await NativeAudio.configure({
  showNotification: true,
  background: true  // Also enable background playback
});

Step 2: Preload audio with metadata

await NativeAudio.preload({
  assetId: 'song1',
  assetPath: 'https://example.com/song.mp3',
  isUrl: true,
  notificationMetadata: {
    title: 'My Song Title',
    artist: 'Artist Name',
    album: 'Album Name',
    artworkUrl: 'https://example.com/artwork.jpg'  // Can be local or remote URL
  }
});

Step 3: Play the audio

// When you play the audio, it will automatically appear in the notification center
await NativeAudio.play({ assetId: 'song1' });

The notification will:

  • Show the title, artist, and album information
  • Display the artwork/album art (if provided)
  • Include media controls (play/pause/stop buttons)
  • Automatically update when audio is paused/resumed
  • Automatically clear when audio is stopped
  • Work on both iOS and Android

Media Controls: Users can control playback directly from:

  • iOS: Control Center, Lock Screen, CarPlay
  • Android: Notification tray, Lock Screen, Android Auto

The media control buttons automatically handle:

  • Play - Resumes paused audio
  • Pause - Pauses playing audio
  • Stop - Stops audio and clears the notification
  • Skip backward - Seeks backward. Default is 15 seconds (seekBackwardSeconds)
  • Skip forward - Seeks forward. Default is 15 seconds (seekForwardSeconds)
  • Previous / Next - Changes the queue item when the queue has more than one track

If you need to keep your app UI synchronized with Android notification or lock-screen controls, listen for the playbackState event. It emits the assetId, resolved state, reason, and the latest position/duration snapshot after remote transport actions.

Android Notification Controls: On Android, a single track shows three actions:

  1. ⏪ Skip backward - Default 15 seconds
  2. ▶️/⏸️ Play/Pause - Toggle playback (icon updates automatically)
  3. ⏩ Skip forward - Default 15 seconds

When a queue has more than one item, Previous and Next are added on the outside. The compact notification then shows Previous, Play/Pause, and Next. Skip backward and skip forward stay on the expanded notification.

Skip buttons are available when showNotification: true. Change the interval with seekBackwardSeconds and seekForwardSeconds in configure().

Notes:

  • All metadata fields are optional
  • Artwork can be a local file path or remote URL
  • The notification only appears when showNotification: true is set in configure()
  • ⚠️ iOS: Enabling notifications will interrupt other apps' audio (see warning above)
  • iOS: Uses MPNowPlayingInfoCenter with MPRemoteCommandCenter
  • Android: Uses MediaSession with NotificationCompat.MediaStyle

Android Background Playback @since 8.2.0

By default, Android pauses audio when the app is backgrounded or the screen is locked. backgroundPlayback: true skips that pause. With showNotification: true, the plugin starts AudioPlaybackService and posts the playback notification as a media foreground service, so Android can keep the process alive.

Android setup

  1. Declare the permissions below in the app AndroidManifest.xml
  2. Call configure() with backgroundPlayback: true and showNotification: true

The service is already merged from the plugin. Do not register a second service.

Step 1: Add the permissions

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

FOREGROUND_SERVICE and FOREGROUND_SERVICE_MEDIA_PLAYBACK are required from Android 14 to start the service. WAKE_LOCK lets the service keep the CPU awake while audio is playing. If the foreground service permissions are missing, playback still starts and the plugin logs a warning. Android may then stop it in the background.

Step 2: Configure and play

import { NativeAudio } from '@capgo/capacitor-native-audio';

await NativeAudio.configure({
  backgroundPlayback: true,
  showNotification: true,
  focus: true,
  seekBackwardSeconds: 15,
  seekForwardSeconds: 30,
});

await NativeAudio.preload({
  assetId: 'meditation',
  assetPath: 'audio/meditation.mp3',
  notificationMetadata: {
    title: 'Meditation Session',
    artist: 'Your App Name',
  },
});

await NativeAudio.play({ assetId: 'meditation' });

The service starts when the notification is shown, and stops when playback is stopped or the notification is cleared. Pause keeps the service so a lock-screen resume still works.

How it works:

  • Without backgroundPlayback: true: the plugin pauses audio when the app enters the background
  • With backgroundPlayback: true: the plugin leaves playback running and, when the notification is visible, holds a media foreground service

iOS: backgroundPlayback is ignored. Enable the Audio background mode (UIBackgroundModes = audio) and use showNotification: true for Control Center and the lock screen.

Notes:

  • Combine backgroundPlayback with showNotification. The service uses that media notification
  • On Android 14 and newer the service type is mediaPlayback

Play Once (Fire-and-Forget) @since 7.11.0

For simple one-shot audio playback (sound effects, notifications, etc.), use playOnce() which handles the entire asset lifecycle automatically:

// Basic usage - automatic cleanup after playback
await NativeAudio.playOnce({
  assetPath: 'audio/notification.mp3',
});

// With volume control
await NativeAudio.playOnce({
  assetPath: 'audio/beep.wav',
  volume: 0.8,
});

// Remote audio with notification metadata
await NativeAudio.playOnce({
  assetPath: 'https://example.com/audio.mp3',
  isUrl: true,
  autoPlay: true,
  notificationMetadata: {
    title: 'Song Name',
    artist: 'Artist Name',
  }
});

// Temporary file with automatic deletion
await NativeAudio.playOnce({
  assetPath: 'file:///path/to/temp-audio.wav',
  deleteAfterPlay: true, // File deleted after playback completes
  volume: 0.5,
});

Advanced: Manual Control

If you need to control playback timing, set autoPlay: false and use the returned assetId:

const { assetId } = await NativeAudio.playOnce({
  assetPath: 'audio/sound.wav',
  autoPlay: false,
});

// Play later when needed
await NativeAudio.play({ assetId });

// Stop if needed (will auto-cleanup)
await NativeAudio.stop({ assetId });

Key Features:

  • ✅ Automatic asset loading and unloading
  • ✅ Cleanup on completion or error
  • ✅ Optional file deletion after playback
  • ✅ Notification metadata support
  • ✅ Works with local files and remote URLs

Notes:

  • Assets are automatically cleaned up after playback completes or on error
  • deleteAfterPlay only works for local file:// URLs, not remote URLs
  • The returned assetId can be used with play(), stop(), unload() methods
  • Manual cleanup via stop() or unload() is optional but supported

Example app

This repository now ships with an interactive Capacitor project under example-app/ that exercises the main APIs on web, iOS, and Android shells.

cd example-app
bun install
bun run dev      # start the web playground
bun run sync     # optional: generate iOS/Android platforms
bun run ios      # open the iOS shell app
bun run android  # open the Android shell app

The UI demonstrates local asset preloading, remote streaming, playback controls, looping, live position updates, and cache clearing for remote audio.

import {NativeAudio} from '@capgo/capacitor-native-audio'


/**
 * This method will load more optimized audio files for background into memory.
 * @param assetPath - relative path of the file, absolute url (file://) or remote url (https://)
 *        assetId - unique identifier of the file
 *        audioChannelNum - number of audio channels
 *        isUrl - pass true if assetPath is a `file://` url
 * @returns void
 */
NativeAudio.preload({
    assetId: "fire",
    assetPath: "assets/sounds/fire.mp3",
    audioChannelNum: 1,
    isUrl: false
});

/**
 * This method will play the loaded audio file if present in the memory.
 * @param assetId - identifier of the asset
 * @param time - (optional) play with seek. example: 6.0 - start playing track from 6 sec
 * @param delay - (optional) delay the audio. default is 0s
 * @param fadeIn - (optional) whether fade in the audio. default is false
 * @param fadeOut - (optional) whether fade out the audio. default is false
 * @param fadeInDuration - (optional) fade in duration in seconds. only used if fadeIn is true. default is 1s
 * @param fadeOutDuration - (optional) fade out duration in seconds. only used if fadeOut is true. default is 1s
 * @param fadeOutStartTime - (optional) time in seconds from the start of the audio to start fading out. only used if fadeOut is true. default is fadeOutDuration before end of audio.
 * @returns void
 */
NativeAudio.play({
    assetId: 'fire',
    // time: 6.0 - seek time
    // volume: 0.4,
    // delay: 1.0,
    // fadeIn: true,
    // fadeOut: true,
    // fadeInDuration: 2,
    // fadeOutDuration: 2
    // fadeOutStartTime: 2
});

/**
 * This method will loop the audio file for playback.
 * @param assetId - identifier of the asset
 * @returns void
 */
NativeAudio.loop({
  assetId: 'fire',
});


/**
 * This method will stop the audio file if it's currently playing.
 * @param assetId - identifier of the asset
 * @param fadeOut - (optional) whether fade out the audio before stopping. default is false
 * @param fadeOutDuration - (optional) fade out duration in seconds. default is 1s
 * @returns void
 */
NativeAudio.stop({
  assetId: 'fire',
  // fadeOut: true,
  // fadeOutDuration: 2
});

/**
 * This method will unload the audio file from the memory.
 * @param assetId - identifier of the asset
 * @returns void
 */
NativeAudio.unload({
  assetId: 'fire',
});

/**
 * This method will set the new volume for a audio file.
 * @param assetId - identifier of the asset
 *        volume - numerical value of the volume between 0.1 - 1.0 default 1.0
 *        duration - time over which to fade to the target volume, in seconds. default is 0s (immediate)
 * @returns void
 */
NativeAudio.setVolume({
  assetId: 'fire',
  volume: 0.4,
  // duration: 2
});

/**
 * this method will get the duration of an audio file.
 * only works if channels == 1
 */
NativeAudio.getDuration({
  assetId: 'fire'
})
.then(result => {
  console.log(result.duration);
})

/**
 * this method will get the current time of a playing audio file.
 * only works if channels == 1
 */
NativeAudio.getCurrentTime({
  assetId: 'fire'
})
.then(result => {
  console.log(result.currentTime);
})

/**
 * this method will set the current time of a playing audio file.
 * @param assetId - identifier of the asset
*  time - time to set the audio, in seconds
 */
NativeAudio.setCurrentTime({
  assetId: 'fire',
  time: 6.0
})

/**
 * This method will return false if audio is paused or not loaded.
 * @param assetId - identifier of the asset
 * @returns {isPlaying: boolean}
 */
NativeAudio.isPlaying({
  assetId: 'fire'
})
.then(result => {
  console.log(result.isPlaying);
})

API

configure(...)

configure(options: ConfigureOptions) => Promise<void>

Configure the audio player

Param Type
options ConfigureOptions

Since: 5.0.0


preload(...)

preload(options: PreloadOptions) => Promise<void>

Load an audio file

Param Type
options PreloadOptions

Since: 5.0.0


playOnce(...)

playOnce(options: PlayOnceOptions) => Promise<PlayOnceResult>

Play an audio file once with automatic cleanup

Method designed for simple, single-shot audio playback, such as notification sounds, UI feedback, or other short audio clips that don't require manual state management.

Key Features:

  • Fire-and-forget: No need to manually preload, play, stop, or unload
  • Auto-cleanup: Asset is automatically unloaded after playback completes
  • Optional file deletion: Can delete local files after playback (useful for temp files)
  • Returns assetId: Can still control playback if needed (pause, stop, etc.)

Use Cases:

  • Notification sounds
  • UI sound effects (button clicks, alerts)
  • Short audio clips that play once
  • Temporary audio files that should be cleaned up

Comparison with regular play():

  • play(): Requires manual preload, play, and unload steps
  • playOnce(): Handles everything automatically with a single call
Param Type
options PlayOnceOptions

Returns: Promise<PlayOnceResult>

Since: 7.11.0


isPreloaded(...)

isPreloaded(options: PreloadOptions) => Promise<{ found: boolean; }>

Check if an audio file is preloaded

Param Type
options PreloadOptions

Returns: Promise<{ found: boolean; }>

Since: 6.1.0


play(...)

play(options: AssetPlayOptions) => Promise<void>

Play an audio file

Param Type
options AssetPlayOptions

Since: 5.0.0


pause(...)

pause(options: AssetPauseOptions) => Promise<void>

Pause an audio file

Param Type
options AssetPauseOptions

Since: 5.0.0


resume(...)

resume(options: AssetResumeOptions) => Promise<void>

Resume an audio file

Param Type
options AssetResumeOptions

Since: 5.0.0


loop(...)

loop(options: Assets) => Promise<void>

Stop an audio file

Param Type
options Assets

Since: 5.0.0


stop(...)

stop(options: AssetStopOptions) => Promise<void>

Stop an audio file

Param Type
options AssetStopOptions

Since: 5.0.0


unload(...)

unload(options: Assets) => Promise<void>

Unload an audio file

Param Type
options Assets

Since: 5.0.0


setVolume(...)

setVolume(options: AssetVolume) => Promise<void>

Set the volume of an audio file

Param Type
options AssetVolume

Since: 5.0.0


setRate(...)

setRate(options: AssetRate) => Promise<void>

Set the rate of an audio file

Param Type
options AssetRate

Since: 5.0.0


setCurrentTime(...)

setCurrentTime(options: AssetSetTime) => Promise<void>

Set the current time of an audio file

Param Type
options AssetSetTime

Since: 6.5.0


getCurrentTime(...)

getCurrentTime(options: Assets) => Promise<{ currentTime: number; }>

Get the current time of an audio file

Param Type
options Assets

Returns: Promise<{ currentTime: number; }>

Since: 5.0.0


getDuration(...)

getDuration(options: Assets) => Promise<{ duration: number; }>

Get the duration of an audio file in seconds

Param Type
options Assets

Returns: Promise<{ duration: number; }>

Since: 5.0.0


getPlaybackState(...)

getPlaybackState(options?: GetPlaybackStateOptions | undefined) => Promise<PlaybackStateEvent>

Snapshot of playback for UI rehydration after navigation or missed events.

Param Type
options GetPlaybackStateOptions

Returns: Promise<PlaybackStateEvent>

Since: 8.5.0


getRate(...)

getRate(options: Assets) => Promise<{ rate: number; }>

Current global playback rate for the asset (same value set with setRate).

Param Type
options Assets

Returns: Promise<{ rate: number; }>

Since: 8.5.0


setQueue(...)

setQueue(options: SetQueueOptions) => Promise<QueueState>

Prepare an ordered queue for podcasts, playlists, or guided sessions. Existing preload assets are reused when ids match.

Param Type
options SetQueueOptions

Returns: Promise<QueueState>

Since: 8.5.0


clearQueue()

clearQueue() => Promise<void>

Since: 8.5.0


getQueueState()

getQueueState() => Promise<QueueState>

Returns: Promise<QueueState>

Since: 8.5.0


queueNext()

queueNext() => Promise<QueueState>

Returns: Promise<QueueState>

Since: 8.5.0


queuePrevious()

queuePrevious() => Promise<QueueState>

Returns: Promise<QueueState>

Since: 8.5.0


queueSelect(...)

queueSelect(options: Assets) => Promise<QueueState>
Param Type
options Assets

Returns: Promise<QueueState>

Since: 8.5.0


queueAdd(...)

queueAdd(options: QueueAddOptions) => Promise<QueueState>

Insert tracks into the current queue without interrupting the item that is already playing.

Param Type
options QueueAddOptions

Returns: Promise<QueueState>

Since: 8.6.0


queueRemove(...)

queueRemove(options: QueueRemoveOptions) => Promise<QueueState>

Remove a track from the current queue. If the playing track is removed, playback continues with the track that takes its place, or stops when the queue is empty.

Param Type
options QueueRemoveOptions

Returns: Promise<QueueState>

Since: 8.6.0


setRepeatMode(...)

setRepeatMode(options: SetRepeatModeOptions) => Promise<void>

Repeat the current item, the whole queue, or neither. This applies to the current session only.

Param Type
options SetRepeatModeOptions

Since: 8.6.0


setSpeaker()

setSpeaker() => Promise<void>

Prefer the built-in speaker. No effect while headphones or Bluetooth are connected.

Since: 8.5.0


setEarpiece()

setEarpiece() => Promise<void>

Route call-style audio to the earpiece on phones.

Since: 8.5.0


getAudioRoute()

getAudioRoute() => Promise<{ route: AudioRouteValue; }>

Returns the current audio output route label. On iOS and Android this reflects the device route (speaker, earpiece, or external). On Web this returns the last route requested via setSpeaker() or setEarpiece() and does not change the real browser output device.

Returns: Promise<{ route: AudioRouteValue; }>

Since: 8.5.0


isPlaying(...)

isPlaying(options: Assets) => Promise<{ isPlaying: boolean; }>

Check if an audio file is playing

Param Type
options Assets

Returns: Promise<{ isPlaying: boolean; }>

Since: 5.0.0


addListener('complete', ...)

addListener(eventName: 'complete', listenerFunc: CompletedListener) => Promise<PluginListenerHandle>

Listen for complete event

Param Type
eventName 'complete'
listenerFunc CompletedListener

Returns: Promise<PluginListenerHandle>

Since: 5.0.0 return {@link CompletedEvent}


addListener('currentTime', ...)

addListener(eventName: 'currentTime', listenerFunc: CurrentTimeListener) => Promise<PluginListenerHandle>

Listen for current time updates Emits every 100ms while audio is playing

Param Type
eventName 'currentTime'
listenerFunc CurrentTimeListener

Returns: Promise<PluginListenerHandle>

Since: 6.5.0 return {@link CurrentTimeEvent}


addListener('playbackState', ...)

addListener(eventName: 'playbackState', listenerFunc: PlaybackStateListener) => Promise<PluginListenerHandle>

Listen for playback state changes, including notification and lock-screen transport controls. Emitted on Android, iOS, and Web when plugin transport methods change playback state.

Param Type
eventName 'playbackState'
listenerFunc PlaybackStateListener

Returns: Promise<PluginListenerHandle>

Since: 8.3.15 return {@link PlaybackStateEvent}


addListener('progress', ...)

addListener(eventName: 'progress', listenerFunc: ProgressListener) => Promise<PluginListenerHandle>

Coarse progress for scrubbers and chapter UI. Interval comes from configure({ progressInterval }).

Param Type
eventName 'progress'
listenerFunc ProgressListener

Returns: Promise<PluginListenerHandle>

Since: 8.5.0


addListener('queueChange', ...)

addListener(eventName: 'queueChange', listenerFunc: QueueChangeListener) => Promise<PluginListenerHandle>

Fires when the active queue item changes.

Param Type
eventName 'queueChange'
listenerFunc QueueChangeListener

Returns: Promise<PluginListenerHandle>

Since: 8.5.0


addListener('audioRouteChange', ...)

addListener(eventName: 'audioRouteChange', listenerFunc: AudioRouteChangeListener) => Promise<PluginListenerHandle>

Fires when the plugin changes routing via setSpeaker() or setEarpiece(). Does not fire for system route changes such as plugging in headphones or Bluetooth.

Param Type
eventName 'audioRouteChange'
listenerFunc AudioRouteChangeListener

Returns: Promise<PluginListenerHandle>

Since: 8.5.0


clearCache()

clearCache() => Promise<void>

Clear the audio cache for remote audio files

Since: 6.5.0


setDebugMode(...)

setDebugMode(options: { enabled: boolean; }) => Promise<void>

Set debug mode logging

Param Type Description
options { enabled: boolean; } - Options to enable or disable debug mode

Since: 6.5.0


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version

Returns: Promise<{ version: string; }>


deinitPlugin()

deinitPlugin() => Promise<void>

Deinitialize the plugin and restore original audio session settings This method stops all playing audio and reverts any audio session changes made by the plugin Use this when you need to ensure compatibility with other audio plugins

Since: 7.7.0


Interfaces

ConfigureOptions

Prop Type Description Default Since
focus boolean focus the audio with Audio Focus
background boolean Play the audio in the background
ignoreSilent boolean Ignore silent mode, works only on iOS setting this will nuke other audio apps
showNotification boolean Show audio playback in the notification center (iOS and Android) When enabled, displays audio metadata (title, artist, album, artwork) in the system notification and Control Center (iOS) or lock screen. Important iOS Behavior: Enabling this option changes the audio session category to .playback with .default mode, which means your app's audio will interrupt other apps' audio (like background music from Spotify, Apple Music, etc.) instead of mixing with it. This is required for the Now Playing info to appear in Control Center and on the lock screen. Trade-offs: - showNotification: true → Shows Now Playing controls, but interrupts other audio - showNotification: false → Audio mixes with other apps, but no Now Playing controls Use this when your app is the primary audio source (music players, podcast apps, etc.). Disable this for secondary audio like sound effects or notification sounds where mixing with background music is preferred.
progressInterval number Seconds between progress events while audio is playing. The currentTime event still fires about every 100ms. 0.5 8.5.0
seekBackwardSeconds number Seconds to skip backward from the notification, lock screen, Control Center, and headset. Values of 0 or less use the default. 15 8.6.0
seekForwardSeconds number Seconds to skip forward from the notification, lock screen, Control Center, and headset. Values of 0 or less use the default. 15 8.6.0
backgroundPlayback boolean Enable background audio playback (Android only) When enabled, audio will continue playing when the app is backgrounded or the screen is locked. The plugin skips the automatic pause/resume logic that normally runs when the app enters the background or returns to the foreground. With showNotification: true, the plugin also starts AudioPlaybackService and posts the media notification as a foreground service notification. That keeps the process eligible to continue playback. The service is registered by the plugin. The app still has to declare the permissions below. If those permissions are missing, playback starts, but Android may stop it in the background. Android manifest xml &lt;uses-permission android:name="android.permission.FOREGROUND_SERVICE" /&gt; &lt;uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /&gt; &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt; WAKE_LOCK lets the service keep the CPU awake while audio is playing. Usage typescript await NativeAudio.configure({ backgroundPlayback: true, showNotification: true, seekBackwardSeconds: 15, seekForwardSeconds: 30 }); On iOS, background playback uses the Audio background mode. backgroundPlayback is ignored there. false 8.2.0

PreloadOptions

Prop Type Description Since
assetPath string Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://) Supported formats: - MP3, WAV (all platforms) - M3U8/HLS streams (iOS and Android) Required unless blob is set.
blob Blob Audio bytes to play. Web only. When set, this is used instead of assetPath. 8.6.0
assetId string Asset Id, unique identifier of the file
volume number Volume of the audio, between 0.1 and 1.0
audioChannelNum number Audio channel number, default is 1
isUrl boolean Is the audio file a URL, pass true if assetPath is a file:// url or a streaming URL (m3u8)
notificationMetadata NotificationMetadata Metadata to display in the notification center when audio is playing. Only used when showNotification: true is set in configure(). See {@link ConfigureOptions.showNotification} for important details about how this affects audio mixing behavior on iOS.
headers Record<string, string> Custom HTTP headers to include when fetching remote audio files. Only used when isUrl is true and assetPath is a remote URL (http/https). Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' } 7.10.0

NotificationMetadata

Metadata to display in the notification center, Control Center (iOS), and lock screen when showNotification is enabled in configure().

Note: This metadata will only be displayed if showNotification: true is set in the configure() method. See {@link ConfigureOptions.showNotification} for important behavior details about audio mixing on iOS.

Prop Type Description
title string The title to display in the notification center
artist string The artist name to display in the notification center
album string The album name to display in the notification center
artworkUrl string URL or local path to the artwork/album art image

PlayOnceResult

Prop Type Description
assetId string The internally generated asset ID for this playback Can be used to control playback (pause, stop, etc.) before completion

PlayOnceOptions

Prop Type Description Default Since
assetPath string Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://) Supported formats: - MP3, WAV (all platforms) - M3U8/HLS streams (iOS and Android) Required unless blob is set.
blob Blob Audio bytes to play. Web only. When set, this is used instead of assetPath. 8.6.0
volume number Volume of the audio, between 0.1 and 1.0 1.0
isUrl boolean Is the audio file a URL, pass true if assetPath is a file:// url or a streaming URL (m3u8) false
autoPlay boolean Automatically start playback after loading true
deleteAfterPlay boolean Delete the audio file from disk after playback completes Only works for local files (file:// URLs), ignored for remote URLs false 7.11.0
notificationMetadata NotificationMetadata Metadata to display in the notification center when audio is playing. Only used when showNotification: true is set in configure(). See {@link ConfigureOptions.showNotification} for important details about how this affects audio mixing behavior on iOS. 7.10.0
headers Record<string, string> Custom HTTP headers to include when fetching remote audio files. Only used when isUrl is true and assetPath is a remote URL (http/https). Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' } 7.10.0

AssetPlayOptions

Prop Type Description
assetId string Asset Id, unique identifier of the file
time number Time to start playing the audio, in seconds
delay number Delay to start playing the audio, in seconds
volume number Volume of the audio, between 0.1 and 1.0
fadeIn boolean Whether to fade in the audio
fadeOut boolean Whether to fade out the audio
fadeInDuration number Fade in duration in seconds. Only used if fadeIn is true. Default is 1s.
fadeOutDuration number Fade out duration in seconds. Only used if fadeOut is true. Default is 1s.
fadeOutStartTime number Time in seconds from the start of the audio to start fading out. Only used if fadeOut is true. Default is fadeOutDuration before end of audio.

AssetPauseOptions

Prop Type Description
assetId string Asset Id, unique identifier of the file
fadeOut boolean Whether to fade out the audio before pausing
fadeOutDuration number Fade out duration in seconds. Default is 1s.

AssetResumeOptions

Prop Type Description
assetId string Asset Id, unique identifier of the file
fadeIn boolean Whether to fade in the audio during resume
fadeInDuration number Fade in duration in seconds. Default is 1s.

Assets

Prop Type Description
assetId string Asset Id, unique identifier of the file

AssetStopOptions

Prop Type Description Default Since
assetId string Asset Id, unique identifier of the file
fadeOut boolean Whether to fade out the audio before stopping
fadeOutDuration number Fade out duration in seconds. Default is 1s.
deactivateAudioSession boolean Deactivate the iOS audio session after this stop. Set this to false when another play() follows immediately, so the session stays active. true 8.6.0

AssetVolume

Prop Type Description
assetId string Asset Id, unique identifier of the file
volume number Volume of the audio, between 0.1 and 1.0
duration number Time over which to fade to the target volume, in seconds. Default is 0s (immediate).

AssetRate

Prop Type Description Default
assetId string Asset Id, unique identifier of the file
rate number Playback rate multiplier. Native engines clamp between 0.25 and 4.0. Pitch is preserved on iOS and Android where the platform supports it. 1.0

AssetSetTime

Prop Type Description
assetId string Asset Id, unique identifier of the file
time number Time to set the audio, in seconds

PlaybackStateEvent

Prop Type Description
assetId string Asset Id of the audio
state PlaybackStateValue Resolved playback state after a local or remote transport action.
reason string Reason for the state change, for example play, pause, remotePlay, or complete.
isPlaying boolean Whether the asset is currently playing.
currentTime number Current playback position in seconds when available.
duration number Total playback duration in seconds when available.

GetPlaybackStateOptions

Prop Type Description
assetId string Asset to inspect. When omitted, uses the active queue item or the last playing asset on native platforms.

QueueState

Prop Type Description
assetId string Asset Id of the currently selected queue item, or empty when the queue is cleared.
index number Zero-based index in the queue, or -1 when empty.
count number Number of items in the queue.
assetIds string[] Ordered asset ids in the queue.

SetQueueOptions

Prop Type Description Default
items QueueItem[] Ordered list of tracks to play.
startIndex number Index of the item to prepare first. 0
autoPlay boolean Start playback after the first item is ready. false

QueueAddOptions

Prop Type Description
items QueueItem[] Tracks to insert into the current queue.
index number Zero-based index to insert at. Omit to append.

QueueRemoveOptions

Prop Type Description
index number Zero-based index to remove.
assetId string Asset id to remove. Used when index is omitted.

SetRepeatModeOptions

Prop Type Description Default Since
mode RepeatMode none stops at the ends of the queue. one replays the current item when it finishes. all plays the next item, wrapping from the last item to the first. 'none' 8.6.0

PluginListenerHandle

Prop Type
remove () => Promise<void>

CompletedEvent

Prop Type Description Since
assetId string Emit when a play completes 5.0.0

CurrentTimeEvent

Prop Type Description Since
currentTime number Current time of the audio in seconds 6.5.0
assetId string Asset Id of the audio 6.5.0

ProgressEvent

Prop Type Description
assetId string Asset Id of the playing item.
position number Current position in seconds.
duration number Duration in seconds when known, otherwise 0.

QueueChangeEvent

Prop Type Description
assetId string
index number
reason string Why the queue selection changed, for example setQueue, next, previous, select, or remoteNext.

AudioRouteChangeEvent

Prop Type Description
route AudioRouteValue Active output route after the change.

Type Aliases

Record

Construct a type with a set of properties K of type T

{ [P in K]: T; }

PlaybackStateValue

'playing' | 'paused' | 'stopped'

QueueItem

One entry in a playback queue. Uses the same fields as {@link PreloadOptions}.

Pick< PreloadOptions, 'assetId' | 'assetPath' | 'isUrl' | 'volume' | 'audioChannelNum' | 'notificationMetadata' | 'headers' >

Pick

From T, pick a set of properties whose keys are in the union K

{ [P in K]: T[P]; }

RepeatMode

'none' | 'one' | 'all'

AudioRouteValue

'speaker' | 'earpiece' | 'external'

CompletedListener

(state: CompletedEvent): void

CurrentTimeListener

(state: CurrentTimeEvent): void

PlaybackStateListener

(state: PlaybackStateEvent): void

ProgressListener

(event: ProgressEvent): void

QueueChangeListener

(event: QueueChangeEvent): void

AudioRouteChangeListener

(event: AudioRouteChangeEvent): void

Development and Testing

Building

bun run build

Testing

This plugin includes native unit coverage plus Maestro smoke tests for the example app on iOS and Android:

  1. Run plugin verification with bun run verify
  2. Build and sync the example app from example-app/
  3. With a booted device and the shell app installed, run the Android smoke flow with bun run test:e2e:android
  4. With a booted simulator and the shell app installed, run the iOS smoke flow with bun run test:e2e:ios
  5. For native unit tests in Xcode, open the example app iOS project with cd example-app && bunx cap open ios and run Product > Test (⌘+U)

The tests cover core functionality including audio asset initialization, playback, volume control, fade effects, and smoke-tested example app playback flows. See the test documentation for more details.

Jelajahi proyek terkait

Memuat…