How to Play Audio in Flutter | Full Audio Player Code Example

In this App Example code, we are going to show you how to play audio files like MP3, WAV, and other audio formats from assets or URL. You will learn to play, pause, resume, stop, seek or jump and get the duration and position of playing audio.

First, you need to add audioplayer Flutter package in your project by adding the following lines in pubspect.yaml file.

dependencies:
  flutter:
    sdk: flutter
  audioplayers: ^0.20.1

Declare Audio Player Object:

AudioPlayer player = AudioPlayer();

Index asset folder in pubspec.yaml file:

flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/audio/

Add your audio files in assets/audio/ folder.

Read file as ByteData and convert it to Unit8List from assets folder.

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/services.dart';
import 'dart:typed_data';
String audioasset = "assets/audio/red-indian-music.mp3";
ByteData bytes = await rootBundle.load(audioasset); //load audio from assets
Uint8List audiobytes = bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);

Play Audio with data loaded from Assets file:

int result = await player.playBytes(audiobytes);
if(result == 1){ //play success
    print("audio is playing.");
}else{
    print("Error while playing audio."); 
}

You can use player.playBytes(bytedata) to play audio files from Unit8List. Here, we loaded the audio file from the asset folder as UNit8List and play it.

int result = await audioPlayer.play(url);
if (result == 1) {
    // success
}

int result = await audioPlayer.play(localPath, isLocal: true);
if (result == 1) {
    // success
}

int result = await player.pause();
if(result == 1){ 
  //pause success
}

int result = await player.resume();
if(result == 1){ 
  //resume success
}

int result = await player.stop();
if(result == 1){ 
  //stop success
}

int result = await player.seek(Duration(milliseconds: 3454));
if(result == 1){ 
  //seek success
}

player.onDurationChanged.listen((Duration d) { //get the duration of audio
    int maxduration = d.inMilliseconds; 
});

You can convert the fetched duration to minutes or seconds.

player.onAudioPositionChanged.listen((Duration  p){
  currentpos = p.inMilliseconds; //get the current position of playing audio
});

This is the listener which is triggered when the audio position is changed while playing audio.

You can download Audio Player App Example:

import 'dart:typed_data';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
         home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int maxduration = 100;
  int currentpos = 0;
  String currentpostlabel = "00:00";
  String audioasset = "assets/audio/red-indian-music.mp3";
  bool isplaying = false;
  bool audioplayed = false;
  late Uint8List audiobytes;

  AudioPlayer player = AudioPlayer();

  @override
  void initState() {
    Future.delayed(Duration.zero, () async {

       ByteData bytes = await rootBundle.load(audioasset); //load audio from assets
       audiobytes = bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);
       //convert ByteData to Uint8List

       player.onDurationChanged.listen((Duration d) { //get the duration of audio
           maxduration = d.inMilliseconds; 
           setState(() {
             
           });
       });

      player.onAudioPositionChanged.listen((Duration  p){
        currentpos = p.inMilliseconds; //get the current position of playing audio

          //generating the duration label
          int shours = Duration(milliseconds:currentpos).inHours;
          int sminutes = Duration(milliseconds:currentpos).inMinutes;
          int sseconds = Duration(milliseconds:currentpos).inSeconds;

          int rhours = shours;
          int rminutes = sminutes - (shours * 60);
          int rseconds = sseconds - (sminutes * 60 + shours * 60 * 60);

          currentpostlabel = "$rhours:$rminutes:$rseconds";

          setState(() {
             //refresh the UI
          });
      });

    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Play Audio in Flutter App"),
            backgroundColor: Colors.redAccent
         ),
         body: Container( 
               margin: EdgeInsets.only(top:50),
               child: Column(
                 children: [

                      Container(
                         child: Text(currentpostlabel, style: TextStyle(fontSize: 25),),
                      ),
                      
                      Container(
                        child: Slider(
                            value: double.parse(currentpos.toString()),
                            min: 0,
                            max: double.parse(maxduration.toString()),
                            divisions: maxduration,
                            label: currentpostlabel,
                            onChanged: (double value) async {
                               int seekval = value.round();
                               int result = await player.seek(Duration(milliseconds: seekval));
                               if(result == 1){ //seek successful
                                    currentpos = seekval;
                               }else{
                                    print("Seek unsuccessful.");
                               }
                            },
                          )
                      ),

                      Container(
                        child: Wrap( 
                            spacing: 10,
                            children: [
                                ElevatedButton.icon(
                                  onPressed: () async {
                                      if(!isplaying && !audioplayed){
                                          int result = await player.playBytes(audiobytes);
                                          if(result == 1){ //play success
                                              setState(() {
                                                 isplaying = true;
                                                 audioplayed = true;
                                              });
                                          }else{
                                              print("Error while playing audio."); 
                                          }
                                      }else if(audioplayed && !isplaying){
                                          int result = await player.resume();
                                          if(result == 1){ //resume success
                                              setState(() {
                                                 isplaying = true;
                                                 audioplayed = true;
                                              });
                                          }else{
                                              print("Error on resume audio."); 
                                          }
                                      }else{
                                          int result = await player.pause();
                                          if(result == 1){ //pause success
                                              setState(() {
                                                 isplaying = false;
                                              });
                                          }else{
                                              print("Error on pause audio."); 
                                          }
                                      }
                                  }, 
                                  icon: Icon(isplaying?Icons.pause:Icons.play_arrow),
                                  label:Text(isplaying?"Pause":"Play")
                                ),

                                ElevatedButton.icon(
                                  onPressed: () async {
                                      int result = await player.stop();
                                      if(result == 1){ //stop success
                                          setState(() {
                                              isplaying = false;
                                              audioplayed = false;
                                              currentpos = 0;
                                          });
                                      }else{
                                          print("Error on stop audio."); 
                                      }
                                  }, 
                                  icon: Icon(Icons.stop),
                                  label:Text("Stop")
                                ),
                            ],
                        ),
                      )

                 ],
               )
          
          )
    );
  } 
}

In this app example, it has audio seek, current position display on Slider and Text, play, pause, resume and stop features.

In this way, you can make an Audio player to play audio, pause, resume, stop, seek features.

No any Comments on this Article


Please Wait...