How to Play Audio Files in Flutter

How to Play Audio Files in Flutter

Flutter does not include built-in support for audio playback, but it offers a rich ecosystem of packages that make it easy to integrate media features. One of the most popular packages for audio playback is audioplayers. This tutorial walks you through the steps to play an audio file from your app’s assets.

Step 1: Create a New Flutter Project

Open your terminal and run the following command to create a new Flutter project:


flutter create audio_demo
cd audio_demo

Step 2: Add Dependencies

Open pubspec.yaml and add the audioplayers package under dependencies:

dependencies:
flutter:
sdk: flutter
audioplayers: ^6.4.0

Then run:

flutter pub get

 

Step 3: Add Audio File to Assets

Create a folder named assets in the root of your project and place your audio file inside it (e.g., assets/sample.mp3).

Update your pubspec.yaml to include the asset:

 

flutter:
assets:
- assets/sample.mp3

Step 4: Implement Audio Playback in Dart

Open lib/main.dart and replace its contents with the following code:

 

</pre>
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

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

class AudioApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: AudioHome(),
debugShowCheckedModeBanner: false,
);
}
}

class AudioHome extends StatefulWidget {
@override
_AudioHomeState createState() =&gt; _AudioHomeState();
}

class _AudioHomeState extends State&lt;AudioHome&gt; {
final AudioPlayer _player = AudioPlayer();

void _playAudio() async {
await _player.play(AssetSource('sample.mp3'));
}

void _pauseAudio() async {
await _player.pause();
}

void _stopAudio() async {
await _player.stop();
}

@override
void dispose() {
_player.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Audio Player')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(onPressed: _playAudio, child: Text('Play')),
ElevatedButton(onPressed: _pauseAudio, child: Text('Pause')),
ElevatedButton(onPressed: _stopAudio, child: Text('Stop')),
],
),
),
);
}
}
<pre>
Step 5: Run the App
Use the following command to launch your app:
flutter run

You should now see a simple UI with buttons to play, pause, and stop the audio file

Notes

  • The AssetSource class is used to reference audio files stored in the assets folder.
  • Always dispose of the AudioPlayer instance to free up resources.
  • You can customize the UI and add features like volume control, seek bar, or background playback.

For more advanced use cases, such as streaming audio or handling multiple tracks, refer to the audioplayers documentation.

 


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *