Make a Music Player In Flutter

 


In this tutorial, I will show you how to build a music Player using Flutter. so without further ado let's start it.


Setup the project

First, create a new project, you can do that with Visual studio code or android studio, choose the editor that you feel comfortable with. and now let's add some packages and some file before we code our app

we will need to add this package called audioplayers

audioplayers: ^0.16.1


And now let's create a new Folder and Call it "Assets"

NB: make sure to call it Assets because we will use Audio cache which access to the Assets Folder

Now add the folder path to your pubspec.yaml file and let's start build our app

 assets:
    - assets/



Now let's start Coding

The Project Source code

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MusicApp(),
    );
  }
}

class MusicApp extends StatefulWidget {
  @override
  _MusicAppState createState() => _MusicAppState();
}

class _MusicAppState extends State<MusicApp> {
  //we will need some variables
  bool playing = false// at the begining we are not playing any song
  IconData playBtn = Icons.play_arrow; // the main state of the play button icon

  //Now let's start by creating our music player
  //first let's declare some object
  AudioPlayer _player;
  AudioCache cache;

  Duration position = new Duration();
  Duration musicLength = new Duration();

  //we will create a custom slider

  Widget slider() {
    return Container(
      width: 300.0,
      child: Slider.adaptive(
          activeColor: Colors.blue[800],
          inactiveColor: Colors.grey[350],
          value: position.inSeconds.toDouble(),
          max: musicLength.inSeconds.toDouble(),
          onChanged: (value) {
            seekToSec(value.toInt());
          }),
    );
  }

  //let's create the seek function that will allow us to go to a certain position of the music
  void seekToSec(int sec) {
    Duration newPos = Duration(seconds: sec);
    _player.seek(newPos);
  }

  //Now let's initialize our player
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _player = AudioPlayer();
    cache = AudioCache(fixedPlayer: _player);

    //now let's handle the audioplayer time

    //this function will allow you to get the music duration
    _player.durationHandler = (d) {
      setState(() {
        musicLength = d;
      });
    };

    //this function will allow us to move the cursor of the slider while we are playing the song
    _player.positionHandler = (p) {
      setState(() {
        position = p;
      });
    };
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //let's start by creating the main UI of the app
      body: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.blue[800],
                Colors.blue[200],
              ]),
        ),
        child: Padding(
          padding: EdgeInsets.only(
            top: 48.0,
          ),
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                //Let's add some text title
                Padding(
                  padding: const EdgeInsets.only(left: 12.0),
                  child: Text(
                    "Music Beats",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 38.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 12.0),
                  child: Text(
                    "Listen to your favorite Music",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 24.0,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ),
                SizedBox(
                  height: 24.0,
                ),
                //Let's add the music cover
                Center(
                  child: Container(
                    width: 280.0,
                    height: 280.0,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30.0),
                        image: DecorationImage(
                          image: AssetImage("assets/image.jpg"),
                        )),
                  ),
                ),

                SizedBox(
                  height: 18.0,
                ),
                Center(
                  child: Text(
                    "Stargazer",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 32.0,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                SizedBox(
                  height: 30.0,
                ),
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(30.0),
                        topRight: Radius.circular(30.0),
                      ),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        //Let's start by adding the controller
                        //let's add the time indicator text

                        Container(
                          width: 500.0,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                "${position.inMinutes}:${position.inSeconds.remainder(60)}",
                                style: TextStyle(
                                  fontSize: 18.0,
                                ),
                              ),
                              slider(),
                              Text(
                                "${musicLength.inMinutes}:${musicLength.inSeconds.remainder(60)}",
                                style: TextStyle(
                                  fontSize: 18.0,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            IconButton(
                              iconSize: 45.0,
                              color: Colors.blue,
                              onPressed: () {},
                              icon: Icon(
                                Icons.skip_previous,
                              ),
                            ),
                            IconButton(
                              iconSize: 62.0,
                              color: Colors.blue[800],
                              onPressed: () {
                                //here we will add the functionality of the play button
                                if (!playing) {
                                  //now let's play the song
                                  cache.play("Stargazer.mp3");
                                  setState(() {
                                    playBtn = Icons.pause;
                                    playing = true;
                                  });
                                } else {
                                  _player.pause();
                                  setState(() {
                                    playBtn = Icons.play_arrow;
                                    playing = false;
                                  });
                                }
                              },
                              icon: Icon(
                                playBtn,
                              ),
                            ),
                            IconButton(
                              iconSize: 45.0,
                              color: Colors.blue,
                              onPressed: () {},
                              icon: Icon(
                                Icons.skip_next,
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}











Make a Music Player In Flutter Make a Music Player In Flutter Reviewed by Medics on October 28, 2020 Rating: 5

20 comments:

  1. Thanks for sharing the knowledge doctor code dev

    ReplyDelete
  2. guitar players feel that practicing their scales and struggling through the basics is hard. Those who are learning under traditional music teachers have it even harder, spending hours and hours on something you can't really figure as part of any song you like. This comes from objective observation as well as personal experience. Guitar cover songs

    ReplyDelete
  3. I have just the same thing as yours but it does not work. Why? my brother!!!

    ReplyDelete
  4. How can i fix this ?

    The setter 'durationHandler' isn't defined for the type 'AudioPlayer'.
    Try importing the library that defines 'durationHandler', correcting the name to the name of an existing setter, or defining a setter or field named 'durationHandler'.

    ReplyDelete
    Replies
    1. Have you fixed it?
      If yes please tell me too🥲🥲

      Delete
  5. https://pressspot.blogspot.com/2018/08/add-autoplay-background-music-on-blogger.html?showComment=1626779862993#c827548218685326696

    ReplyDelete
  6. Very well written about Make a Music Player In Flutter. If you want videos of Make a Music Player In Flutter, please download vidmate. Vidmate is a free app where you don't need to spend money to use this app, you can watch any video from this app whenever you want. With the Vidmate app, you can easily download the videos that you want to save on your device and you can also download those videos and share them with your friends. You can also download Make a Music Player In Flutter and Vidmate from 9apps

    ReplyDelete
  7. Error: Cannot run with sound null safety, because the following dependencies
    don't support null safety:

    - package:audioplayers
    - package:path_provider
    - package:uuid
    - package:path_provider_linux
    - package:path_provider_windows
    - package:path_provider_platform_interface
    - package:crypto
    - package:convert
    - package:xdg_directories
    - package:plugin_platform_interface

    For solutions, see https://dart.dev/go/unsound-null-safety


    FAILURE: Build failed with an exception.

    * Where:
    Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1005

    * What went wrong:
    Execution failed for task ':app:compileFlutterBuildDebug'.
    > Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

    * Get more help at https://help.gradle.org

    BUILD FAILED in 21s
    Exception: Gradle task assembleDebug failed with exit code 1

    ReplyDelete
  8. Kodi Mod Apk has a simple goal: make it easy for friends to watch videos together no matter where they are in the world.

    https://apkmodule.com/kodi-mod-apk/

    ReplyDelete
  9. I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. constantly hating young thug download

    ReplyDelete
  10. CL 4K UHD Player- High Quality Video Player app allows you to watch your favorite movies, shows and other videos in Ultra HD quality. You can watch high quality videos from your device or SD card and stream from web. This app also works as whatsapp status downloader.
    Install CL 4K UHD Player- High Quality Video Player on your android device and enjoy 4K ultra HD videos anytime, anywhere.

    Visit here:- HD video player app

    ReplyDelete
  11. The cyberika graphics are stunning, and this is very helpful to enjoy the game because the perfect graphics are the main reason for a successful game. The theme of the cyberika apk is awesome, and the animation is eye-catching.
    Check out.
    https://apkomex.com/download-cyberika-mod-apk/

    ReplyDelete
  12. Cricket league MOD APK
    is the pro version of this game. You can create your team of your favorite players in the cricket league.

    ReplyDelete
  13. This is a fantastic piece article. We have a selection of articles and blog posts to help readers. These articles are related to Celebrity NetWorth, Bio, Wealth, ralated and more.Below, you can see the most recent blog posts.

    Deion Sanders Net Worth

    ReplyDelete
  14. This article is outstanding. To assist readers, we offer a variety of articles and blog posts. These articles cover a variety of topics, including Celebrity NetWorth, Bio, Wealth, and more.See the most current blog entries down below.

    Scrub Daddy Net Worth

    ReplyDelete

  15. This essay is excellent. We provide a range of articles and blog posts to help readers. Numerous subjects are covered in these articles, including Celebrity NetWorth, Bios, Wealth, and others.The most recent blog posts are listed below.

    Blueface Net Worth

    ReplyDelete
  16. Thank you for this amazing article. Here are some extraordinary posts for you. These posts concern Apk Download, Mod Apk Free Download ralated etc.
    Look below to see the latest blog posts.

    Pikachu App Free Download

    ReplyDelete

-->
Powered by Blogger.