Git Product home page Git Product logo

pawangjain / flutter-assetsaudioplayer Goto Github PK

View Code? Open in Web Editor NEW

This project forked from florent37/flutter-assetsaudioplayer

0.0 1.0 0.0 95.3 MB

Play simultaneously music/audio from assets/network/file directly from Flutter, compatible with android / ios / web, displays notifications

Home Page: https://pub.dartlang.org/packages/assets_audio_player

License: Apache License 2.0

Kotlin 18.77% Ruby 3.55% Swift 14.96% Objective-C 0.59% Dart 61.35% Shell 0.33% HTML 0.46%

flutter-assetsaudioplayer's Introduction

๐ŸŽง assets_audio_player ๐Ÿ”Š

pub package

Play music/audio stored in assets files (simultaneously) directly from Flutter (android / ios / web).

You can also use play audio files from network using their url

try online : https://flutter-assets-audio-player.web.app

flutter:
  assets:
    - assets/audios/
AssetsAudioPlayer.newPlayer().open(
    Audio("assets/audios/song1.mp3"),
    autoPlay: true,
);

sample1 sample1

๐Ÿ“ฅ Import

dependencies:
  assets_audio_player: ^1.4.7+4

Works with flutter: ">=1.12.13+hotfix.6 <2.0.0", be sure to upgrade your sdk

๐ŸŒ Web support

And if you wan web support, enable web then add

dependencies:
  assets_audio_player_web: ^1.4.7+4

You like the package ? buy me a kofi :)

Buy Me a Coffee at ko-fi.com

Audio Source Android iOS Web
Asset file (asset path) โœ… โœ… โœ…
Network file (url) โœ… โœ… โœ…
Local file (path) โœ… โœ… โœ…
Network LiveStream (url) โœ… โœ… โœ…
Commands Android iOS Web
Play โœ… โœ… โœ…
Pause โœ… โœ… โœ…
Stop โœ… โœ… โœ…
Seek(position) โœ… โœ… โœ…
SeekBy(position) โœ… โœ… โœ…
Forward(speed) โœ… โœ… โœ…
Rewind(speed) โœ… โœ… โœ…
Next โœ… โœ… โœ…
Prev โœ… โœ… โœ…
Feature Android iOS Web
Multiple players โœ… โœ… โœ…
Open Playlist โœ… โœ… โœ…
system notification โœ… โœ… ๐Ÿšซ
Respect System silent mode โœ… โœ… ๐Ÿšซ
Pause on phone call โœ… โœ… ๐Ÿšซ
Audio Widget โœ… โœ… โœ…
Properties Android iOS Web
Loop โœ… โœ… โœ…
get/set Volume โœ… โœ… โœ…
get/set Play Speed โœ… โœ… โœ…
Listeners Android iOS Web
Listener onReady(completeDuration) โœ… โœ… โœ…
Listener currentPosition โœ… โœ… โœ…
Listener finished โœ… โœ… โœ…
Listener buffering โœ… โœ… โœ…
Listener volume โœ… โœ… โœ…
Listener Play Speed โœ… โœ… โœ…

๐Ÿ“ Import assets files

No needed to copy songs to a media cache, with assets_audio_player you can open them directly from the assets.

  1. Create an audio directory in your assets (not necessary named "audios")
  2. Declare it inside your pubspec.yaml
flutter:
  assets:
    - assets/audios/

๐Ÿ› ๏ธ Getting Started

final assetsAudioPlayer = AssetsAudioPlayer();

assetsAudioPlayer.open(
    Audio("assets/audios/song1.mp3"),
);

You can also play network songs from url

final assetsAudioPlayer = AssetsAudioPlayer();

try {
    await assetsAudioPlayer.open(
        Audio.network("http://www.mysite.com/myMp3file.mp3"),
    );
} catch (t) {
    //mp3 unreachable
}

And play songs from file

//create a new player
final assetsAudioPlayer = AssetsAudioPlayer();

assetsAudioPlayer.open(
    Audio.file(FILE_URI),
);
assetsAudioPlayer.playOrPause();
assetsAudioPlayer.play();
assetsAudioPlayer.pause();
assetsAudioPlayer.seek(Duration to);
assetsAudioPlayer.seekBy(Duration by);
assetsAudioPlayer.forwardRewind(double speed);
//if positive, forward, if negative, rewind
assetsAudioPlayer.stop();

Notifications

notification

notification

on iOS, it will use MPNowPlayingInfoCenter

  1. Add metas inside your audio
final audio = Audio("/assets/audio/country.mp3", 
    metas: Metas(
            title:  "Country",
            artist: "Florent Champigny",
            album: "CountryAlbum",
            image: MetasImage.asset("assets/images/country.jpg"), //can be MetasImage.network
          ),
   );
  1. open with showNotification: true
_player.open(audio, showNotification: true)

โ›“ Play in parallel / simultaneously

You can create new AssetsAudioPlayer using AssetsAudioPlayer.newPlayer(), which will play songs in a different native Media Player

This will enable to play two songs simultaneously

You can have as many player as you want !

///play 3 songs in parallel
AssetsAudioPlayer.newPlayer().open(
    Audio("assets/audios/song1.mp3")
);
AssetsAudioPlayer.newPlayer().open(
    Audio("assets/audios/song2.mp3")
);

//another way, with create, open, play & dispose the player on finish
AssetsAudioPlayer.playAndForget(
    Audio("assets/audios/song3.mp3")
);

Each player has an unique generated id, you can retrieve or create them manually using

final player = AssetsAudioPlayer.withId(id: "MY_UNIQUE_ID");

๐Ÿ—„๏ธ Playlist

assetsAudioPlayer.open(
  Playlist(
    assetAudioPaths: [
      "assets/audios/song1.mp3",
      "assets/audios/song2.mp3"
    ]
  )
);

assetsAudioPlayer.next();
assetsAudioPlayer.prev();
assetsAudioPlayer.playAtIndex(1);

Audio Widget

If you want a more flutter way to play audio, try the AudioWidget !

sample

//inside a stateful widget

bool _play = false;

@override
Widget build(BuildContext context) {
  return Audio.assets(
     path: "assets/audios/country.mp3",
     play: _play,
     child: RaisedButton(
           child: Text(
               _play ? "pause" : "play",
           ),
           onPressed: () {
               setState(() {
                 _play = !_play;
               });
           }
      ),
      onReadyToPlay: (duration) {
          //onReadyToPlay
      },
      onPositionChanged: (current, duration) {
          //onReadyToPlay
      },
  );
}

How to ๐Ÿ›‘ stop ๐Ÿ›‘ the AudioWidget ?

Just remove the Audio from the tree ! Or simply keep play: false

๐ŸŽง Listeners

All listeners exposes Streams Using RxDart, AssetsAudioPlayer exposes some listeners as ValueObservable (Observable that provides synchronous access to the last emitted item);

๐ŸŽต Current song

//The current playing audio, filled with the total song duration
assetsAudioPlayer.current //ValueObservable<PlayingAudio>

//Retrieve directly the current played asset
final PlayingAudio playing = assetsAudioPlayer.current.value;

//Listen to the current playing song
assetsAudioPlayer.current.listen((playingAudio){
    final asset = playingAudio.assetAudio;
    final songDuration = playingAudio.duration;
})

โŒ› Current song duration

//Listen to the current playing song
final duration = assetsAudioPlayer.current.value.duration;

โณ Current position (in seconds)

assetsAudioPlayer.currentPosition //ValueObservable<Duration>

//retrieve directly the current song position
final Duration position = assetsAudioPlayer.currentPosition.value;

return StreamBuilder(
    stream: assetsAudioPlayer.currentPosition,
    builder: (context, asyncSnapshot) {
        final Duration duration = asyncSnapshot.data;
        return Text(duration.toString());  
    }),

or use a PlayerBuilder !

PlayerBuilder.currentPosition(
     player: _assetsAudioPlayer,
     builder: (context, duration) {
       return Text(duration.toString());  
     }
)

โ–ถ IsPlaying

boolean observable representing the current mediaplayer playing state

assetsAudioPlayer.isPlaying // ValueObservable<bool>

//retrieve directly the current player state
final bool playing = assetsAudioPlayer.isPlaying.value;

//will follow the AssetsAudioPlayer playing state
return StreamBuilder(
    stream: assetsAudioPlayer.isPlaying,
    builder: (context, asyncSnapshot) {
        final bool isPlaying = asyncSnapshot.data;
        return Text(isPlaying ? "Pause" : "Play");  
    }),

or use a PlayerBuilder !

PlayerBuilder.isPlaying(
     player: _assetsAudioPlayer,
     builder: (context, isPlaying) {
       return Text(isPlaying ? "Pause" : "Play");  
     }
)

๐Ÿ”Š Volume

Change the volume (between 0.0 & 1.0)

assetsAudioPlayer.setVolume(0.5);

The media player can follow the system "volume mode" (vibrate, muted, normal) Simply set the respectSilentMode optional parameter as true

_player.open(PLAYABLE, respectSilentMode: true);

https://developer.android.com/reference/android/media/AudioManager.html?hl=fr#getRingerMode()

https://developer.apple.com/documentation/avfoundation/avaudiosessioncategorysoloambient

Listen the volume

return StreamBuilder(
    stream: assetsAudioPlayer.volume,
    builder: (context, asyncSnapshot) {
        final double volume = asyncSnapshot.data;
        return Text("volume : $volume");  
    }),

or use a PlayerBuilder !

PlayerBuilder.volume(
     player: _assetsAudioPlayer,
     builder: (context, volume) {
       return Text("volume : $volume");
     }
)

โœ‹ Finished

Called when the current song has finished to play,

it gives the Playing audio that just finished

assetsAudioPlayer.playlistAudioFinished //ValueObservable<Playing>

assetsAudioPlayer.playlistAudioFinished.listen((Playing playing){
    
})

Called when the complete playlist has finished to play

assetsAudioPlayer.playlistFinished //ValueObservable<bool>

assetsAudioPlayer.playlistFinished.listen((finished){
    
})

๐Ÿ” Looping

final bool isLooping = assetsAudioPlayer.loop; //true / false

assetsAudioPlayer.loop = true; //set loop as true

assetsAudioPlayer.isLooping.listen((loop){
    //listen to loop
})

assetsAudioPlayer.toggleLoop(); //toggle the value of looping

Network Policies (android/iOS)

Android only allow HTTPS calls, you will have an error if you're using HTTP, don't forget to add INTERNET permission and seet usesCleartextTraffic="true" in your AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

iOS only allow HTTPS calls, you will have an error if you're using HTTP, don't forget to edit your info.plist and set NSAppTransportSecurity to NSAllowsArbitraryLoads

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

๐ŸŒ Web Support

Web support is using import_js_library to import the Howler.js library

The flutter wrapper of Howler has been exported in another package : https://github.com/florent37/flutter_web_howl

๐ŸŽถ Musics

All musics used in the samples came from https://www.freemusicarchive.org/

flutter-assetsaudioplayer's People

Contributors

adamkoch avatar dustin-graham avatar faiyyaz avatar florent37 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.