Open In App

How to Add Audio File in Flutter Application?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Flutter is a well known tool for developing cross platform applications. It is considered a good choice among developers because of the single code base policy for all types of OS and devices. Flutter engine provides support to vast libraries and file types, its easy to develop beautifull UI by adding fonts, images and widgets.

Flutter engine don't support audio files hence playing audio is not as easy as viewing the image from assets folder. Every cloud has a silver lining - but no worries, Flutter provides the solution too. There are many plugins that can be integrated within the app to play audio. In this article, we will learn to use the audio files from the asset folder using assets_audio_players plugin.

Step-by-Step Implementation of Audio Player Application

Step 1 : Creating a Flutter App

Open the terminal and type below command to create flutter project.

flutter create audio_player

Project Structure

project_structure


Step 2 : Add the dependency and audio files to pubspec.yaml file

You can either manually add following dependency to pubspec.yaml file.

dependency_audio_app

As the project is created, you will find main.dart file inside lib folder, create assets folder as mentioned in above project structure. Also upload any audio named ringtone.mp3 and image named placeholder.png to assets folder. Import the asset in pubspec.yaml.

flutter:
assets:
- assets/ringtone.mp3
- assets/placeholder.png

Or you can run following command to load dependency.

flutter pub get

Step 3 : Code for main.dart

The UI consist of an static image and buttons to play and stop audio. The code integrates the function _playAudio and _stopAudio from the plugin to play and stop the audio file.

main.dart
import 'package:flutter/material.dart';
import 'package:assets_audio_player/assets_audio_player.dart';

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

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

class audio extends StatefulWidget {
  @override
  _audioState createState() => _audioState();
}

class _audioState extends State<audio> {
  final AssetsAudioPlayer _assetsAudioPlayer = AssetsAudioPlayer();

  // Play audio
  void _playAudio() {
    _assetsAudioPlayer.open(
      Audio("assets/ringtone.mp3"),
    );
  }

  // Stop audio
  void _stopAudio() {
    _assetsAudioPlayer.stop();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
            title: const Text('Audio player Application', style: TextStyle(fontSize: 25)),
            backgroundColor: Colors.green[700],
            toolbarHeight: 70,
            elevation: 5,
            shadowColor: Colors.green[700],
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20))
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(
              'assets/placeholder.png', 
              width: 200,
              height: 400, 
            ),
            const SizedBox(height: 6),
            ElevatedButton(
              onPressed: _playAudio,
              child: const Text('Play' , style: TextStyle(fontSize: 10, letterSpacing: 1.0,fontWeight: FontWeight.bold, color: Colors.black), textAlign: TextAlign.center,),
                    style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green[700],
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10)),
                            padding: EdgeInsets.only(
                                right: 20, left: 25, top: 5, bottom: 15))
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _stopAudio,
              
              child: const Text('Stop' , style: TextStyle(fontSize: 10, letterSpacing: 1.0,fontWeight: FontWeight.bold, color: Colors.black), textAlign: TextAlign.center,),
                    style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green[700],
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10)),
                            padding: EdgeInsets.only(
                                right: 20, left: 25, top: 15, bottom: 15))
                  ),
          ],
        ),
      ),
    );
  }

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


Step 4 : Run the application

Save the project and enter below command to run the application.

flutter run

Output :


Next Article
Article Tags :

Similar Reads