A simple audio player app using Dart and Flutter

A simple audio player app using Dart and Flutter

Hola everyone!! Music is no doubt one of the best healers in the world. It has magic in itself. So, here I bring the procedure of creating simple customised flutter app that will play our favourite song whenever we want! We can play the music, pause or stop it as per our desire.

This app is my small tribute to our beloved late actor Sushant Singh Rajput :)

Pre-Requisites: i) Flutter installed ii) Dart SDK installed iii) Visual Studio Code as IDE iv) Android Studio for launching emulator (although we can use our own smartphone also after certain configuration)

So let's get started....

First, we will create the workspace for our app, using the pre - created test app that comes with the flutter software.

flutter create music_app

Folder structure: Running the above command will create our environment followed by downloading all the environment requirements for an app. Our main code will be in the main.dart file inside lib folder. I will be creating the UI of the app in home.dart file inside ui folder of lib. I would require the audio that will be played as an asset to the app. The audio will be placed in a sub-folder named audios inside folder assets. The assets folder will also contain any image files if we use them as other assets. The overall folder structure is as below:-

No alt text provided for this image

Assets: Flutter apps can include both code and assets (sometimes called resources). An asset is a file that is bundled and deployed with your app, and is accessible at runtime (also without internet). Common types of assets include static data (for example, JSON files), configuration files, icons, audio and images (JPEG, WebP, GIF, PNG, BMP, WAV and WBMP). Here, I will be using the audio file (the song that will be played) as an asset, and evidently since it will be an asset, the song can be played even in the absence of internet.

  • Note that we need to convert our mp3 audio into wav file before moving on. For this, there are many online converters available on the internet.

For accessing the asset, we need to update the pubspec.yml file as below and save it so that the command flutter pub get runs automatically and loads the asset.

No alt text provided for this image

Cool! Now let's look upon the flutter packages required for playing audio. For this, we head on to the https://pub.dev/ site and look for audioplayers package.

This is the package that we need:-

No alt text provided for this image

To install the package the dependencies, we update the package version in our pubspec.yml file as below:-

No alt text provided for this image

Now we are all set to start the dart coding part - the backbone of our app. We would first create the app UI and import the asset. As already stated, this will be done in home.dart file. Let's code step-by step.

  1. Import the required packages.
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';

2. Declare the audio variables using appropriate classes.

AudioPlayer audioplayer = new AudioPlayer();
AudioCache audio = new AudioCache(fixedPlayer: audioplayer);
bool play = false;
bool stop = true;

3. Define the functions for displaying an image followed by playing, pausing and stopping the music.

audioplay() {
  if (play == false || stop == true) {
    audio.play("audios/MainTumhara.wav");
    play = true;
    stop = false;
  }
}


audiopause() {
  if (play == true) {
    audioplayer.pause();
    play = false;
  }
}


audiostop() {
  if (play == true || stop == false) {
    audioplayer.stop();
    play = false;
    stop = true;
  }
}


myImage() {
  var url =
      'https://raw.githubusercontent.com/SaranyaChattopadhyay/Flutter-pictures/master/musicImg.jpg';
  var img = Image.network(url);
  return img;
}

4. The overall UI of the app will be coded inside the main MyHome() function.

MaterialApp MyHome() {
  var home = Scaffold(
    appBar: AppBar(
      title: Text("All About Music"),
      backgroundColor: Colors.greenAccent.shade400,
    ),
    body: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          alignment: Alignment.center,
          width: 300,
          height: 50,
          child: Text(
            "Dil Bechara",
            style: TextStyle(
              fontStyle: FontStyle.italic,
              fontSize: 30,
            ),
          ),
        ),
        Container(
          child: myImage(),
          alignment: Alignment.center,
          width: 500,
          height: 400,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              onPressed: audioplay,
              child: Icon(Icons.play_arrow),
            ),
            RaisedButton(
              onPressed: audiopause,
              child: Icon(Icons.pause),
            ),
            RaisedButton(
              onPressed: audiostop,
              child: Icon(Icons.stop),
            )
          ],
        )
      ],
    ),
  
    backgroundColor: Colors.cyan.shade100;
);

5. Return the design of the app.

var design = MaterialApp(
    home: home,
    debugShowCheckedModeBanner: false,
  );


  return design;
}

Now, it's time for the main.dart file for the app, the heart of the app that contains the main function. Hot reload option has been enabled in the app.

import 'package:flutter/material.dart';
import 'ui/home.dart';


void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHome();
  
  }
}

# All the codes uploaded in my GitHub, link provided in the post. Do get a reference if required.

After coding part is over, we can start running the app by: Run --> Start debugging. On providing the appropriate emulator or selecting the devise, our app will be built.

No alt text provided for this image

The overall look-and-feel of the app comes out as shown. Pressing the play button pays the song. Pressing the pause button pauses it temporarily which can be resumed by pressing the play button again. The stop button stops the audio permanently.

No alt text provided for this image

Hence, our app has been built as per we intended to. We can now enjoy this immensely soothing song created by the great A.R. Rahman on our own audio-player.

That's all guys! Thanks for giving me a read...

Hriddha Bhowmik

Software Engineer, Capgemini India ???? Guidewire Certified Associate Developer ?

4 年

Wonderfully done ??

要查看或添加评论,请登录

Saranya Chattopadhyay的更多文章

社区洞察

其他会员也浏览了