A Flutter audio plugin (Swift/Java) to play remote or local audio files on iOS / Android / MacOS and Web

Overview

AudioPlayer

A Flutter audio plugin (Swift/Java) to play remote or local audio files on iOS / Android / MacOS and Web.

Online demo

Features

  • Android / iOS / MacOS / Web
    • play remote file
    • play local file ( not for the web)
    • stop
    • pause
    • onComplete
    • onDuration / onCurrentPosition
    • seek
    • mute

screenshot

Usage

Example

To use this plugin :

  dependencies:
    flutter:
      sdk: flutter
    audioplayer: 0.8.1
    audioplayer_web: 0.7.1
  • Instantiate an AudioPlayer instance
//...
AudioPlayer audioPlugin = AudioPlayer();
//...

Player Controls

audioPlayer.play(url);

audioPlayer.pause();

audioPlayer.stop();

Status and current position

The dart part of the plugin listen for platform calls :

//...
_positionSubscription = audioPlayer.onAudioPositionChanged.listen(
  (p) => setState(() => position = p)
);

_audioPlayerStateSubscription = audioPlayer.onPlayerStateChanged.listen((s) {
  if (s == AudioPlayerState.PLAYING) {
    setState(() => duration = audioPlayer.duration);
  } else if (s == AudioPlayerState.STOPPED) {
    onComplete();
    setState(() {
      position = duration;
    });
  }
}, onError: (msg) {
  setState(() {
    playerState = PlayerState.stopped;
    duration = new Duration(seconds: 0);
    position = new Duration(seconds: 0);
  });
});

Do not forget to cancel all the subscriptions when the widget is disposed.

iOS

⚠️ iOS App Transport Security

By default iOS forbids loading from non-https url. To cancel this restriction edit your .plist and add :

<key>NSAppTransportSecuritykey>
<dict>
    <key>NSAllowsArbitraryLoadskey>
    <true/>
dict>

Background mode

cf. enable background audio

MacOS

Add this to entitlements files ( cf. DebugProfile.entitlements )

    <key>com.apple.security.network.clientkey>
    <true/>

cf. Flutter MacOS security

Troubleshooting

  • If you get a MissingPluginException, try to flutter build apk on Android, or flutter build ios

Getting Started with Flutter

For help getting started with Flutter, view our online documentation.

For help on editing plugin code, view the documentation.

Comments
  • MissingPluginException(No implementation found for method play on channel bz.rxla.flutter/audio)

    MissingPluginException(No implementation found for method play on channel bz.rxla.flutter/audio)

    I ran the init method from the example provided, and as soon as I play the sound, I get the error. The play method is taken from the exaple as well. The only thing I replaced was the url to the sound.

    opened by TheDumbfounds 23
  • build apk failed

    build apk failed

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    A problem occurred configuring root project 'audioplayer'.
    > No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
    
    
    The plugin audioplayer could not be built due to the issue above.
    
    Doctor summary (to see all details, run flutter doctor -v):
    [✓] Flutter (Channel beta, v1.12.13+hotfix.6, on Mac OS X 10.15.2 19C57, locale zh-Hans-CN)
     
    [✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    [✓] Xcode - develop for iOS and macOS (Xcode 11.3)
    [✓] Chrome - develop for the web
    [✓] Android Studio (version 3.5)
    [✓] Connected device (2 available)
    
    opened by badboy-tian 6
  • Failed assertion: line 81 pos 16: '_state == AudioPlayerState.PLAYING': is not true

    Failed assertion: line 81 pos 16: '_state == AudioPlayerState.PLAYING': is not true

    Hi,

    I'm building a messaging app and I'm getting the error on the title line when playing a local file. I'm calling the audioPlayer.play() withing the message element. Since there are a lot of them I'm building the AudioPlayer object when tapping on an audio message and than trying to dispose it afterwards. In doing so the audio does play but the app crashes right afterwards with the error mentioned above. Any help is greatly appreciated.

    # Here I initialized the AudioPlayer
    audioPlayer = new AudioPlayer();
    
    # Here I play the audio file, it crashes here 
    await audioPlayer.play(_audioPath, isLocal: true);
    setState(() => playerState = PlayerState.playing);
    
    opened by DevilWarrior 6
  • Play audio from assets

    Play audio from assets

    Allow users to play audio files included as flutter assets.

    Usage is simple:

    1. add an audio file to the dart project and include it in pubspec.yaml like so:
    flutter:
      assets:
        - audio/sample.m4a
    
    1. call playAsset() on the player like so:
    Future _playAsset() async {
      final result = await audioPlayer.playAsset("audio/sample.m4a");
      if (result == 1) setState(() => playerState = PlayerState.playing);
    }
    

    everything else works as documented.

    opened by dustin-graham 6
  • Audio player unresponsive after stopping and creating new instance in a new isolate

    Audio player unresponsive after stopping and creating new instance in a new isolate

    I can't really explain this well in the short title. I'm using the ryanheise/audio_service plugin. This plugin launches an isolate for background dart code execution upon starting the audio service. In this isolate code (which I'll refer to as an "audio task") I implement callbacks and start, pause play, etc. an AudioPlayer instance. If, however, I stop the audio task, and start a new one (creating a new AudioPlayer instance in a new isolate), I can start playback okay, but nothing else works. I can't play, pause or stop the player. The futures for the AudioPlayer methods do finish, though. The method calls don't broadcast anything in the onPlayerStateChanged stream, either.

    If you need my code to debug, I'd happily put up a private repo.

    opened by hacker1024 4
  • IOS connection lost

    IOS connection lost

    First I've downloaded the file then click on Play Local

    *** First throw call stack: ( 0 CoreFoundation 0x000000010409212b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x00000001046a9f41 objc_exception_throw + 48 2 CoreFoundation 0x0000000104113024 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132 3 CoreFoundation 0x0000000104014f78 ___forwarding___ + 1432 4 CoreFoundation 0x0000000104014958 _CF_forwarding_prep_0 + 120 5 audioplayer 0x000000010394e04a -[AudioplayerPlugin togglePlay:isLocal:] + 170 6 audioplayer 0x000000010394da93 __45-[AudioplayerPlugin handleMethodCall:result:]_block_invoke + 563 7 audioplayer 0x000000010394d691 -[AudioplayerPlugin handleMethodCall:result:] + 1169 8 Flutte<…> Lost connection to device.

    I like this plugin I want to make an app around it !

    opened by Solido 4
  • Support of Obj-C version?

    Support of Obj-C version?

    I am trying to test audioplayer plugin with the FriendlyChat source.

    When I do "edit/convert/To Current Swift Syntax" and I selected all items in this screen

    and I get this message

    then I add plugins to yaml and run, I get error

    Launching lib/main.dart on iPhone SE in debug mode...

    Running pod install...

    Error running pod install: Exit code 1 from: pod install

    Error launching application on iPhone SE.

    opened by EasonPai 4
  • AudioplayerPlugin.h not found

    AudioplayerPlugin.h not found

    Hi, using the plugin in the Simulator or on my phone in debug mode works flawlessly. But when I implement it in my app and build it using the 'archive' command it complains about the missing header file. Any idea why?

    The same happens also with the example project

    screen shot 2018-07-26 at 6 06 27 pm
    opened by PeterPan4d 3
  • iOS 14.2 AudioPlayer will not play: [The operation could not be completed]

    iOS 14.2 AudioPlayer will not play: [The operation could not be completed]

    I am using a pre-signed HTTPS Amazon AWS S3 URL for the audio stream. On iOS 13 and using audioplayer 0.5.2 I had no issues with my current code.

    I've tried replacing the pre-signed HTTPS AWS S3 URL with a static one: https://luan.xyz/files/audio/ambient_c_motion.mp3 but still the player does not play.

    On iOS 14 and audioplayer 0.8.1 the audio will not play, and the audioPlayer.onPlayerStateChanged.listen() throws an error of [The operation could not be completed]

    Is this being actively developed or should I jump ship?

    iOS 14.2 flutter 1.22.4 Xcode 12.2 dart 2.10.3 audioplayer 0.8.1

    opened by ooglek 2
  • Compatibility with newer gradle versions

    Compatibility with newer gradle versions

    The minSdk version should not be declared in the android manifest file. You can move the version from the manifest to the defaultConfig in the build.gradle file

    Newer gradle version do not support uses-sdk tag inside AndroidManifest.xml anymore.

    Needs to be moved to build.gradle.

    opened by nstrelow 2
  • Is this package dead? Alternatives?

    Is this package dead? Alternatives?

    @rxlabz Is this repository still maintained?

    It seems like there are a lot of open issues and pull requests without any replies.

    Just shoot us an update so people know if they need to move on to a different package.

    opened by nstrelow 2
  • app collapse when playing, occasionally suddenly

    app collapse when playing, occasionally suddenly

    W/Choreographer(15953): Frame time is 17.409424 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase. W/Choreographer(15953): Frame time is 16.27997 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase. D/ViewRootImpl(15953): DisplayId = 0 I/MediaBrowserService(15953): No root for client com.android.bluetooth from service android.service.media.MediaBrowserService$ServiceBinder$1 D/AndroidRuntime(15953): Shutting down VM E/AndroidRuntime(15953): FATAL EXCEPTION: main E/AndroidRuntime(15953): Process: com.freejoy.music, PID: 15953 E/AndroidRuntime(15953): java.lang.RuntimeException: Unable to stop service bz.rxla.audioplayer.AudioplayerPlugin@40c9b0d: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.session.MediaSession.release()' on a null object reference E/AndroidRuntime(15953): at android.app.ActivityThread.handleStopService(ActivityThread.java:4048) E/AndroidRuntime(15953): at android.app.ActivityThread.access$1900(ActivityThread.java:233) E/AndroidRuntime(15953): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1917) E/AndroidRuntime(15953): at android.os.Handler.dispatchMessage(Handler.java:106) E/AndroidRuntime(15953): at android.os.Looper.loop(Looper.java:233) E/AndroidRuntime(15953): at android.app.ActivityThread.main(ActivityThread.java:7225) E/AndroidRuntime(15953): at java.lang.reflect.Method.invoke(Native Method) E/AndroidRuntime(15953): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499) E/AndroidRuntime(15953): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:962) E/AndroidRuntime(15953): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.session.MediaSession.release()' on a null object reference E/AndroidRuntime(15953): at bz.rxla.audioplayer.AudioplayerPlugin.onDestroy(AudioplayerPlugin.java:199) E/AndroidRuntime(15953): at android.app.ActivityThread.handleStopService(ActivityThread.java:4028) E/AndroidRuntime(15953): ... 8 more I/Process (15953): Sending signal. PID: 15953 SIG: 9 Lost connection to device.

    AndroidManifest.xml

    opened by gateshibill 1
  • Unable to load asset : assets/audio/note1.wav

    Unable to load asset : assets/audio/note1.wav

    I am trying to play local files in my xylophone app but it keeps throwing this error and doesn't play any note.

    Error:

    E/flutter (22928): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Unable to load asset: assets/audio/note1.wav
    E/flutter (22928): #0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:224:7)
    E/flutter (22928): <asynchronous suspension>
    E/flutter (22928): #1      AudioCache.fetchToMemory (package:audioplayers/src/audio_cache.dart:89:22)
    E/flutter (22928): <asynchronous suspension>
    E/flutter (22928): #2      AudioCache.load (package:audioplayers/src/audio_cache.dart:115:31)
    E/flutter (22928): <asynchronous suspension>
    E/flutter (22928): #3      AudioCache.play (package:audioplayers/src/audio_cache.dart:159:17)
    E/flutter (22928): <asynchronous suspension>
    E/flutter (22928): 
    

    main.dart:

    import 'package:flutter/material.dart';
    import 'package:audioplayers/audioplayers.dart';
    
    void main() {
      runApp(Xylophone());
    }
    
    class Xylophone extends StatefulWidget {
      const Xylophone({Key? key}) : super(key: key);
    
      @override
      _XylophoneState createState() => _XylophoneState();
    }
    
    void playSound(int noteNumber) {
      final player = AudioCache();
      player.play('audio/note$noteNumber.wav');
    }
    
    class _XylophoneState extends State<Xylophone> {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Scaffold(
            body: SafeArea(
              child: Column(
                children: [
                  Container(
                    color: Colors.red,
                    child: MaterialButton(
                      onPressed: () {
                        playSound(1);
                      },
                      child: Text('Do'),
                    ),
                  ),
                  Container(
                    color: Colors.orange,
                    child: MaterialButton(
                      onPressed: () {
                        playSound(2);
                      },
                      child: Text('Re'),
                    ),
                  ),
                  Container(
                    color: Colors.yellow,
                    child: MaterialButton(
                      onPressed: () {
                        playSound(3);
                      },
                      child: Text('Mi'),
                    ),
                  ),
                  Container(
                    color: Colors.green,
                    child: MaterialButton(
                      onPressed: () {
                        playSound(4);
                      },
                      child: Text('Fa'),
                    ),
                  ),
                  Container(
                    color: Colors.teal,
                    child: MaterialButton(
                      onPressed: () {
                        playSound(5);
                      },
                      child: Text('Si'),
                    ),
                  ),
                  Container(
                    color: Colors.blue,
                    child: MaterialButton(
                      onPressed: () {
                        playSound(6);
                      },
                      child: Text('La'),
                    ),
                  ),
                  Container(
                    color: Colors.purple,
                    child: MaterialButton(
                      onPressed: () {
                        playSound(7);
                      },
                      child: Text('Sol'),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }
    

    And pubsec.yaml:

    name: xylophone
    description: A new Flutter project.
    
    publish_to: 'none'
    
    version: 1.0.0+1
    
    environment:
      sdk: ">=2.12.0 <3.0.0"
    
    dependencies:
      flutter:
        sdk: flutter
    
      cupertino_icons: ^1.0.2
      audioplayers: ^0.19.1
    
    dev_dependencies:
      flutter_test:
        sdk: flutter
    
    flutter:
    
      uses-material-design: true
    
    assets:
      - assets/audio
    

    Please provide detailed answers and helpful solutions.

    opened by Wincynin 2
  • AudioPlayerState.PAUSED is not detected on Web

    AudioPlayerState.PAUSED is not detected on Web

    Listening for state changes to the audio player with the following and not seeing any AudioPlayerState.RESUME also, even thought the ENUM talks about resume, there is no such function.

    /// Paused. The user can [resume] the playback without providing the URL. PAUSED,

        player.onPlayerStateChanged.listen((AudioPlayerState s) {
          playerState = s;
          print(playerState);
        });
    

    audioplayer: ^0.8.1 audioplayer_web: ^0.7.1

    Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel master, 2.1.0-13.0.pre.293, on Mac OS X 10.15.7 19H2 darwin-x64, locale en-NZ) [!] Android toolchain - develop for Android devices (Android SDK version 30.0.2) ! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses [✓] Xcode - develop for iOS and macOS [✓] Chrome - develop for the web [✓] Android Studio (version 4.1) [✓] VS Code (version 1.55.1) [✓] Connected device (2 available)

    opened by digitalrbnz 0
Releases(0.8.0)
Play simultaneously music/audio from assets/network/file directly from Flutter, compatible with android / ios / web / macos, displays notifications

?? assets_audio_player ?? Play music/audio stored in assets files (simultaneously) directly from Flutter (android / ios / web / macos). You can also u

Florent CHAMPIGNY 651 Dec 24, 2022
Just_audio: a feature-rich audio player for Android, iOS, macOS and web

just_audio just_audio is a feature-rich audio player for Android, iOS, macOS and web. Mixing and matching audio plugins The flutter plugin ecosystem c

Ensar Yusuf Yılmaz 2 Jun 28, 2022
Apps For streaming audio via url (Android, iOS & Web ). Developed with Dart & Flutter ❤

Flutter Sleep App (Dicoding Submission : Learn to Make Flutter Apps for Beginners) Stream Great collection of high-definition sounds that can be mixed

Utrodus Said Al Baqi 13 Nov 29, 2022
Music Player app made with Just audio library and Local database Hive.

Music Player app made with Just audio library and Local database Hive. Find the free and Royelty music with Happy Rock application. The app contains information about singers and you can make your own playlist with Songs.Happy rock App's features are same as the real music app like spotify, amazon music etc.

Ansh rathod 17 Dec 22, 2022
Flutter (web-only at this moment) plugin for recording audio (using the microphone).

Microphone Flutter (web-only at this moment) plugin for recording audio (using the microphone). Getting started To learn more about the plugin and get

null 28 Sep 26, 2022
Audio Recorder Jordan AlcarazAudio Recorder [156⭐] - Record audio and store it locally by Jordan Alcaraz.

Audio recorder Record audio and store it locally Usage To use this plugin, add audio_recorder as a dependency in your pubspec.yaml file. Android Make

Jordan Alcaraz 172 Jan 4, 2023
A Flutter package for both android and iOS which provides Audio recorder

social_media_recorder A Flutter package for both android and iOS which provides

subhikhalifeh 16 Dec 29, 2022
WaVe - an audio streaming platform which gives the best user experience without any compromise in the audio quality

WaVe is an audio streaming platform which gives the best user experience without any compromise in the audio quality, and there is even space for the users to explore their creativity. And makes it more efficient with the AI features.

OmarFayadhd 1 May 31, 2022
Playify is a Flutter plugin for play/pause/seek songs, fetching music metadata, and browsing music library.

Playify Playify is a Flutter plugin for play/pause/seek songs, fetching music metadata, and browsing music library. Playify was built using iOS's Medi

Ibrahim Berat Kaya 32 Dec 14, 2022
Audio classification Tflite package for flutter (iOS & Android).

Audio classification Tflite package for flutter (iOS & Android). Can also support Google Teachable Machine models.

Michael Nguyen 47 Dec 1, 2022
Minimalistic local music player built with flutter for android.

Nano Music Player Simple local music player built with flutter. It uses the audioplayer plugin to play files, and path_provider to locate the external

Jan Hrastnik 34 Dec 17, 2022
WazPlay is just a music app written in flutter and service to download song and play it.

wazplay Introduction WazPlay is just a music app written in flutter and service to download song and play it. WazPlay is the first product for Waz and

Zaw Lin Tun 4 Dec 8, 2022
Flutter plugin that can support audio recording and level metering

flutter_audio_recorder English | 简体中文 Flutter Audio Record Plugin that supports Record Pause Resume Stop and provide access to audio level metering pr

RMBR ONE 108 Dec 13, 2022
Flutter plugin for sound. Audio recorder and player.

Flutter Sound user: your documentation is there The CHANGELOG file is here Overview Flutter Sound is a Flutter package allowing you to play and record

null 764 Jan 2, 2023
A Flutter audio-plugin to playing and recording sounds

medcorder_audio Flutter record/play audio plugin. Developed for Evrone.com Funded by Medcorder Medcorder.com Getting Started For help getting started

Evrone 106 Oct 29, 2022
Flutter plugin for sound. Audio recorder and player.

Sounds Sounds is a Flutter package allowing you to play and record audio for both the android and ios platforms. Sounds provides both a high level API

Brett Sutton 75 Dec 8, 2022
Flutter plugin for selecting multiple images from the Android and iOS image library

Flutter plugin for selecting multiple images from the Android and iOS image library, taking new pictures with the camera, and edit them before using such as rotating, cropping, adding sticker/filters.

Weta Vietnam 91 Dec 19, 2022
A Flutter media player plugin for iOS and android based on ijkplayer

Flutter media player plugin for android/iOS based on ijkplayer.

于飞白呀 1.4k Jan 4, 2023
A opensource, minimal and powerful audio player for android

A opensource, minimal and powerful audio player for android

Milad 7 Nov 2, 2022