Zambrella
Zambrella

Reputation: 91

Is there a way to control system music in Flutter?

I would like to be able to pause/play and skip music that is playing in a different app (e.g. Spotify/Youtube Music/etc.). Is there a way to control this within a Flutter app?

Thanks in advance!

Upvotes: 4

Views: 603

Answers (1)

Zach Wright
Zach Wright

Reputation: 66

There is not currently a package for this that I know of. I have an android only app that I am trying to get working, the solution is to make a platform channel and then do something to this effect.

package com.example.myapp

import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import androidx.annotation.RequiresApi
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
  private val METHOD_CHANNEL_NAME = "com.example.myapp/media_control"
  private var methodChannel: MethodChannel? = null
  private var audioManager: AudioManager? = null;

  @RequiresApi(Build.VERSION_CODES.O)
  override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
      super.configureFlutterEngine(flutterEngine)

      setupChannels(this, flutterEngine.dartExecutor.binaryMessenger)
  }

  @RequiresApi(Build.VERSION_CODES.O)
  override fun onCreate(savedInstanceState: Bundle?) {
      audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
      super.onCreate(savedInstanceState)
  }

  @RequiresApi(Build.VERSION_CODES.O)
  private fun setupChannels(mainActivity: MainActivity, binaryMessenger: BinaryMessenger) {
      methodChannel = MethodChannel(binaryMessenger, METHOD_CHANNEL_NAME)
      methodChannel!!.setMethodCallHandler { call, result ->
            if(call.method == "pause") {
                sendMediaButton(KeyEvent.KEYCODE_MEDIA_PAUSE)
                result.success("Success");
            }
            else if (call.method == "play") {
                sendMediaButton(KeyEvent.KEYCODE_MEDIA_PLAY)
                result.success("Success");
            }
            else if (call.method == "skipNext") {
                sendMediaButton(KeyEvent.KEYCODE_MEDIA_NEXT)
                result.success("Success");
            }
            else if (call.method == "skipPrevious") {
                sendMediaButton(KeyEvent.KEYCODE_MEDIA_PREVIOUS)
                result.success("Success");
            }
      }
  }

    private fun sendMediaButton(keyCode: Int) {
        var keyEvent = KeyEvent(KeyEvent.ACTION_DOWN, keyCode)
        audioManager!!.dispatchMediaKeyEvent(keyEvent)

        keyEvent = KeyEvent(KeyEvent.ACTION_UP, keyCode)
        audioManager!!.dispatchMediaKeyEvent(keyEvent)
    }

}

Upvotes: 1

Related Questions