X

Flutter Audio Player Tutorial

 

Flutter Audio Player :

In Flutter Audio Player tutorial we will be going through the process of playing audio file from the local assets folder in our flutter app.

In general we sometimes need to play a audio clip in the file notifying some task completion or on message or call received through our app like whatsapp, facebook, skype, google duo and more apps.

Playing a audio/music file we mostly used to play songs in common user point of view, in this tutorial we will play a music file on our app using flutter platform.

Audio streaming apps are mostly built using these advanced audio players which can provide high quality output.

Now a days people are using the online music apps like Gaana, Savan for playing songs instead of the manually storing the songs in device, here the songs are loaded from internet.

 

Flutter Audio Player Video Tutorial :

Explore the tutorial below for a deeper understanding and more comprehensive implementation details.

 

Project Structure :

This image provides the project structure for flutter audio player integration in your app.

 

pubspec.yaml :

We need to add dependencies audioplayers, path, provider and also here try to provide the latest version numbers so that there won’t be any code level issues.

dependencies:
  flutter:
    sdk: flutter
  audioplayers:
  provider: ^3.0.0+1

 

 

Add assets to pubspec to access and play audio in flutter audio player

assets:
  - sample.mp3

 

 

main.dart :

Initialize with void main() and specify the default class MyApp()

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

 

 

Declare audioCache, advancedPlayer

AudioCache audioCache = AudioCache(); 
AudioPlayer advancedPlayer = AudioPlayer();

 

 

Initialize headless service for iOS

@override
void initState() {
  super.initState();

  _initializeAudioService();
}

void _initializeAudioService() {
  if (Platform.isIOS && audioCache.fixedPlayer != null) {
    audioCache.fixedPlayer.startHeadlessService();
  }
}

 

 


Specify Future<int> _getDuration() to get the duration of the audio file through async call

Future<int> _getDuration() async {
  File audioFile = await audioCache.load('sample.mp3');
  await advancedPlayer.setUrl(
    audioFile.path,
  );
  await Future.delayed(Duration(seconds: 2)); // Delay for stability
  int duration = await advancedPlayer.getDuration();
  return duration;
}

 

 

Capture the audio file duration and display on to screen using Text widget

Widget getLocalFileDuration() {
  return FutureBuilder<int>(
    future: _getDuration(),
    builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return CircularProgressIndicator(); // or any other loading indicator
      } else if (snapshot.hasError) {
        return Text('Error: ${snapshot.error}');
      } else {
        return Text(
          'sample.mp3 duration is: ${Duration(milliseconds: snapshot.data)}',
        );
      }
    },
  );
}

 

 


Declare a raised button

ElevatedButton(
  onPressed: () => audioCache.play('sample.mp3'),
  child: Text("Play Audio"),
),

 

 

onPressed call the play function

onPressed: () => audioCache.play('sample.mp3')

 

 

call the call duration to display duration on screen when audio file is being played

getLocalFileDuration(),

 

 

Full Code :

Providing the full source code for flutter audio player integrations.

import 'dart:async';
import 'dart:io';

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

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  AudioCache audioCache = AudioCache();
  AudioPlayer advancedPlayer = AudioPlayer();

  @override
  void initState() {
    super.initState();
    _initializeAudioService();
  }

  Future<void> _initializeAudioService() async {
    if (Platform.isIOS) {
      if (audioCache.fixedPlayer != null) {
        audioCache.fixedPlayer.startHeadlessService();
      }
    }
  }

  Future<int> _getDuration() async {
    File audiofile = await audioCache.load('sample.mp3');
    await advancedPlayer.setUrl(
      audiofile.path,
    );
    int duration = await Future.delayed(Duration(seconds: 2), () => advancedPlayer.getDuration());
    return duration;
  }

  Widget getLocalFileDuration() {
    return FutureBuilder<int>(
      future: _getDuration(),
      builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
        return Text(
          'sample.mp3 duration is: ${Duration(milliseconds: snapshot.data)}',
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('audioplayers Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Play Local Asset \'sample.mp3\':'),
            SizedBox(height: 30),
            RaisedButton(
              child: Text("Play Audio"),
              onPressed: () => audioCache.play('sample.mp3'),
            ),
            SizedBox(height: 30),
            getLocalFileDuration(),
          ],
        ),
      ),
    );
  }
}

 

 

Flutter audio player output :

This screen depicts the usage of the flutter audio player

If you have any questions, feel free to drop them in the comments below. If you enjoyed this tutorial, show us some love by liking and sharing for more exciting updates

abhishek:
Related Post

This website uses cookies.