Play Music in flutter: The simplest way to play music in flutte app

Play music in flutter
Play music in a flutter

In this simple app, we will build an app that will play an mp3 file from your asset folder. Take any mp3 file or song and place it in your assets folder.

For playing any music file we will use a plugin whose name is just_audio. We only need this plugin you don’t need to add any other.

step-1

Create a flutter project

flutter create example_music_app

step – 2

Go to this URL: https://pub.dev/packages/just_audio_background

and add just an audio plugin to your app you can do it via command line like flutter pub add just_audio (make sure you are in your project dir)
Or
copy paste just_audio: ^0.9.27 to your pubspec.yaml under dependencies.

 just_audio: ^0.9.27

Step – 3

Inside your project, create a folder, name its assets, and place the audio file that you want to play.

Step – 4

Make a home page, You can design on your own but for this app, I’m making it as simple as possible. Make a file name it home_page_music.dart. And create a stateful class HomePageMusic and don’t forget to import just_audio package:

import 'package:just_audio/just_audio.dart';

Step – 5

Inside _HomePageMusicState Make a bool variable displaying for changing the playing icon and make a
an instance of AudioPlayer that comes from just the audio plugin.

bool isPlaying = false;
late AudioPlayer audioPlayer;

Step – 6

Initialize audioPlayer inside initState.

@override
void initState() {
     super.initState();
     audioPlayer = AudioPlayer();
}

Step – 7

Make an async function playAudioFile like this:

playAudioFile() async {
   await audioPlayer.setAsset('assets/audio/song1.mp3');
   audioPlayer.play();
}

. Dispose of audioPlayer in dispose of method

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

Step – 8

This _HomePageState should return Scaffold. In the body of the scaffold take a center widget and for the child
for this center take a column and for the first child of the column place an Inkwell widget like this.

InkWell(
    onTap: () async {
          await playAudioFile();
             setState(() {
               isPlaying = true;
            });
          },
    child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text('Tap to play',
 
             style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
),

and for the second child place IconButton like this.

IconButton(
        onPressed: () async {
          if (audioPlayer.playing) {
            audioPlayer.pause();

            setState(() {
              isPlaying = false;
            });
          } else {
            audioPlayer.play();
            setState(() {
              isPlaying = true;
            });
          }
        },
        icon: Icon(
          isPlaying ? Icons.pause_circle : Icons.play_arrow_outlined,
          size: 60,
        ),
      ),

Step – 9

And now your app is ready when you click on the text ‘Tap to play’ it starts playing the audio file and when you tap on the icon it will stop the audio. If you again click on ‘Tap to play’ it will start the song again.

The play icon will act as a play/pause button you can play or pause the audio by clicking on it.

Step – 10

The complete code for HomePage is

import 'package:just_audio/just_audio.dart';
import 'package:flutter/material.dart';

class HomePageMusic extends StatefulWidget {
  const HomePageMusic({Key? key}) : super(key: key);

  @override
  State<HomePageMusic> createState() => _HomePageMusicState();
}

class _HomePageMusicState extends State<HomePageMusic> {
  bool isPlaying = false;
  late AudioPlayer audioPlayer;

  @override
  void initState() {
    super.initState();
    audioPlayer = AudioPlayer();
  }

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

  playAudioFile() async {
    await audioPlayer.setAsset('assets/audio/song1.mp3');
    audioPlayer.play();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Music Player')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
              onTap: () async {
                await playAudioFile();
                setState(() {
                  isPlaying = true;
                });
              },
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text('Tap to play',
                    style:
                        TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
              ),
            ),
            IconButton(
              onPressed: () async {
                if (audioPlayer.playing) {
                  audioPlayer.pause();
                  setState(() {
                    isPlaying = false;
                  });
                } else {
                  audioPlayer.play();
                  setState(() {
                    isPlaying = true;
                  });
                }
              },
              icon: Icon(
                isPlaying ? Icons.pause_circle : Icons.play_arrow_outlined,
                size: 60,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.

Remember FlutterDecode.com

Leave a Comment