Flutter Music Player App

Creating the flutter music player app using Method Channel.

What is Method Channel

MethodChannel is a functionality which lets you write custom platform specific code in the native language whether its java/kotlin for Android or swift/objective c for IOS and allows you to call platform specific API.

platformChannel Diagram

For More Information : https://flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-java-tab

  1. Create a new flutter project.
  2. Coding java part.
  3. Listing all the mp3 files in listview.Builder
  4. Implementing the play/pause functionality.

1. Creating the new project

1.1 In MainActivity.java.

MethodChannel channel;
private static final String channelName = "channelVersion1";
AudioClass audioClass;

now implement the MethodChannel.MethodCallHandler and override these two methods

 @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);


        channel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(),channelName);
        channel.setMethodCallHandler(this);

        audioClass = new AudioClass(getApplicationContext());
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        String mcall = methodCall.method;

        switch (mcall){
            case "getAllSong":      // method name
                result.success(getAllSong());
                break;
            case "playSong":
                audioClass.playSong(methodCall.argument("path"));
        }
    }

call this method to return all song from method

    private List<Object> getAllSong(){
        return audioClass.fetchSongs();
    }

Now Create a new AudioClass.java Class

    Context context;

    public AudioClass(Context context) {
        this.context = context;
    }

Now code the method to fetch all mp3 files.

 protected List<Object> fetchSongs(){

        List<Model> list = new ArrayList<>();
        Model model;

        ContentResolver contentResolver = context.getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        Cursor cursor = contentResolver.query(uri,null,null,null,null);

        if(cursor == null){
            Log.d("cursorMsg","Something went wrong");
        }else if(!cursor.moveToNext()){
            Log.d("cursorMsg","No file found in storage");
        }else{

            do{
                int title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
                int path = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);

                String songTitle = cursor.getString(title);
                String songPath = cursor.getString(path);

                model = new Model(songPath,songTitle);
                list.add(model);
            }while (cursor.moveToNext());


            cursor.close();
        }
        List<Object> mlist = new ArrayList();
        for(Model m : list){
            mlist.add(m.toJson());
        }

        return mlist;
    }

now to play the song method

protected void playSong(String path){
        MediaPlayer mediaPlayer = new MediaPlayer();

        Log.d("qwerty",path);
        try{
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

Now Code the Model.java class

public class Model {
    String path;
    String title;

    public Model(String path, String title) {
        this.path = path;
        this.title = title;
    }

    public HashMap<String,String> toJson(){
        HashMap<String,String> hashList = new HashMap<>();
        hashList.put("title",title);
        hashList.put("path",path);

        return hashList;
    }
}

Now coding the dart file

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:music_player_flutter/model.dart';

void main(){
  runApp(
    MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: MyApp(),
        ),
      ),
    )
  );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  static const platform = MethodChannel("channelVersion1");  // method channel name

  List<Model> songList;
  Model model;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    songList = new List();

  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
        future: getAllSong(),
        builder: (BuildContext context,snap){
          return snap.hasData ? songListView() : Center(child: CircularProgressIndicator(),);
        }
      ),
    );
  }

  Widget songListView(){
    return ListView.builder(
        itemCount: songList.length,
        itemBuilder: (BuildContext context, pos) {
          return ListTile(
            onTap: (){
              _playSong(songList[pos].path);
            },
            title: Text(songList[pos].title),
          );
        });
  }
  Future<List> getAllSong() async{
    var title, path = "";
    List<dynamic> list = await platform.invokeMethod("getAllSong");  // method name

    var song = list.map((data) => Model.fromJson(data)).toList();

    for(var file in song){
      title = file.title;
      path = file.path;

      model = new Model(title,path);
      songList.add(model);
    }

    return songList;
  }

  _playSong(String path){
    platform.invokeMethod("playSong",{"path":path});    // method name {argument key}
  }

  // working fine
}

Model.dart file

class Model{

  String _title;
  String _path;

  Model(this._title, this._path);

  String get path => _path;

  set path(String value) {
    _path = value;
  }

  String get title => _title;

  set title(String value) {
    _title = value;
  }

  Model.fromJson(Map map){
    _title = map['title'];
    _path = map['path'];
  }
}

Leave a Comment