使用MediaBrowserServiceCompat进行音乐播放

时间:2018-08-29 18:52:55

标签: android kotlin audio-player android-music-player

我尝试了不同的方法,但遗憾的是它们都没有起作用。我可以收集我的音乐文件,但在这一点上,我尝试不播放它们。我试图在MainActivity中获取音乐文件,但不确定如何从“ mMediaBrowser”变量中获取音乐文件。我使用已知的MediaID进行了进一步尝试,但是当我按下按钮时没有任何反应。谁能帮我?

MainActivity:

package com.name.mediabrowsertest

import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.media.AudioManager
import android.media.MediaDataSource
import android.media.session.MediaController
import android.os.Build

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaBrowserServiceCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import android.view.View
import android.widget.ImageView


class MainActivity : AppCompatActivity() {
    private lateinit var mMediaBrowser: MediaBrowserCompat
    fun buildTransportControls(){
        mMediaBrowser.subscribe(mMediaBrowser.root,object: MediaBrowserCompat.SubscriptionCallback(){})
        //mMediaBrowser.getItem("")

        Log.i("EXTRAS",mMediaBrowser.extras.toString())


        var mPlayPause = findViewById<ImageView>(R.id.imageView)
        //Attach listen to button
        mPlayPause.setOnClickListener(object: View.OnClickListener {
            override fun onClick(v : View ){
                var pbSate = MediaControllerCompat.getMediaController(this@MainActivity).playbackState.playbackState
                if(pbSate == PlaybackStateCompat.STATE_PLAYING){
                    Log.i("1","11111")
                    MediaControllerCompat.getMediaController(this@MainActivity).transportControls.pause()
                }else{
                    Log.i("1","22222")
                    MediaControllerCompat.getMediaController(this@MainActivity).transportControls.playFromMediaId("Böug",null)
                    MediaControllerCompat.getMediaController(this@MainActivity).transportControls.play()

                    //MediaControllerCompat.getMediaController(this@MainActivity).transportControls.playFromMediaId()


                }
            }
        })
        var  mediaController = MediaControllerCompat.getMediaController(this@MainActivity)

        //Show Init state
        var metadat = mediaController.metadata
        var pbState = mediaController.playbackState

        //Register Callback to stay synced
        mediaController.registerCallback(controllerCallback)



    }
    val controllerCallback = object : MediaControllerCompat.Callback() {
        override fun onMetadataChanged(metadat:MediaMetadataCompat){

            Log.i("Musik",metadat.toString())

        }

        override fun onPlaybackStateChanged(state :PlaybackStateCompat){}
    }

    private val mConnectionCallbacks = object : MediaBrowserCompat.ConnectionCallback() {
        override fun onConnected() {
            Log.i("Connection","Connecting")
            // Get the token for the MediaSession
            val token = mMediaBrowser.sessionToken

            // Create a MediaControllerCompat
            val mediaController = MediaControllerCompat(this@MainActivity,token)

            // Save the controller
            MediaControllerCompat.setMediaController(this@MainActivity, mediaController)

            // Finish building the UI
            buildTransportControls()
        }

        override fun onConnectionSuspended() {
            // The Service has crashed. Disable transport controls until it automatically reconnects
            Log.i("ERROR","Connection Suspended")
        }

        override fun onConnectionFailed() {
            // The Service has refused our connection
            Log.i("ERROR","Connection Failed")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.i("Hello World","Hello")
        permissionRequest()
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            //Create MediaBrowser Service
            mMediaBrowser = MediaBrowserCompat(this,
                    ComponentName(this, MediaPlaybackService::class.java),
                    mConnectionCallbacks,
                    null)
        }

        Log.i("Hello World","Hello2")


    }

    override fun onStart() {
        super.onStart()
        mMediaBrowser.connect()

    }

    override fun onResume() {
        super.onResume()
        volumeControlStream = AudioManager.STREAM_MUSIC
    }

    override fun onStop() {
        super.onStop()
        if(MediaControllerCompat.getMediaController(this@MainActivity) != null){
            MediaControllerCompat.getMediaController(this@MainActivity).unregisterCallback(controllerCallback)

        }
        mMediaBrowser.disconnect()
    }


    fun permissionRequest(){
        val permissions = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)

        if(permissions != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE
            ),101)
        }



    }

}

服务:

package com.name.mediabrowsertest


import android.media.MediaDescription
import android.media.MediaMetadata
import android.media.browse.MediaBrowser
import android.media.session.MediaSession
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaBrowserServiceCompat
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import com.name.mediabrowsertest.Services.contentcatalogs.MusicLibrary


class MediaPlaybackService: MediaBrowserServiceCompat(){

    //private val MY_MEDIA_ROOT_ID  = "MediaStore.Audio.Media.EXTERNAL_CONTENT_URI"
    private val MY_MEDIA_ROOT_ID ="root"

    private lateinit var mMediaSession: MediaSessionCompat
    private lateinit var mStateBuilder : PlaybackStateCompat.Builder
    private var  MySessionCallback =object : MediaSessionCompat.Callback() {
        override fun onPause() {
            super.onPause()
        }

        override fun onPlay() {
            super.onPlay()
        }
    }

    override fun onCreate() {
        super.onCreate()
        //Create the MediaSession
        mMediaSession = MediaSessionCompat(this,"PLAYER")
        //Setting the necessary Flags (Media Buttons)
        mMediaSession.setFlags(
                MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS)
        //Set an inital PlaybackStatewith ACTION_BUTTONS, so Media  buttons can start the player
        mStateBuilder = PlaybackStateCompat.Builder().setActions(
                PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE)
        //Set our PLaybackState for the MediaSession
        mMediaSession.setPlaybackState(mStateBuilder.build())

        //Handles callbacks from Media Controller MySessionCalback is a PlaeHolder
        mMediaSession.setCallback(MySessionCallback)
        //Set SessionToken so Activites can communicate with it
        sessionToken = mMediaSession.sessionToken



    }

    override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {
        var mediaItems:ArrayList<MediaBrowserCompat.MediaItem> = ArrayList()


        var albums = MusicLibrary(this@MediaPlaybackService).getMusic()
        for(item in MusicLibrary.MusicFiles){
            val songList = MediaBrowserCompat.MediaItem(item,
                    MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)
            mediaItems.add(songList)
        }


        Log.i("MEDIA_ITEMS",mediaItems.toString())
        result.sendResult(mediaItems)

    }

    override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? {

        return BrowserRoot(MY_MEDIA_ROOT_ID,null)

        }



}

如果需要,可以使用contentListener:

package com.name.mediabrowsertest.Services.contentcatalogs

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.graphics.drawable.Drawable
import android.net.Uri
import android.provider.MediaStore
import android.support.v4.media.MediaDescriptionCompat
import android.util.Log
import com.name.mediabrowsertest.R
import java.io.FileNotFoundException


class MusicLibrary(val context: Context) {

    companion object {
        lateinit var albums: ArrayList<String>
        var MusicFiles = arrayListOf<MediaDescriptionCompat>()
    }

    var desc= arrayListOf<MediaDescriptionCompat>()
    var music_Artist = arrayListOf<String>()
    var music_CoverID = arrayListOf<Drawable>()
    var music_Duration = arrayListOf<Int>()
    var album_Title = arrayListOf<String>()


    @SuppressLint("NewApi")
    fun getMusic() {

        val contentResolver = context.contentResolver
        var songUri: Uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
        var songCursor: Cursor = contentResolver.query(songUri, null, null, null, null)

        //Defining the Uri for the Album covers
        val artworkUri = Uri.parse("content://media/external/audio/albumart")
        var albumArtUri: Uri
        var albumDrawable: Drawable

        if (songCursor != null && songCursor.moveToFirst()) {
            //Getting the Position of the stored values

            var albumCoverId: Int = songCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)
            var songDuration = songCursor.getColumnIndex(MediaStore.Audio.Media.DURATION)


            var albumTitle = songCursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM)



            do {
                //Ensure that atleast on Element is in album_Title
                if(!album_Title.isEmpty()) {
                    //Test if album is already in array
                    if(album_Title.contains(songCursor.getString(albumTitle))) {
                        //If album is already in Array skip loop
                        continue
                    }

                }

                album_Title.add(songCursor.getString(albumTitle))


                //getting the Uri of the Album
                albumArtUri = ContentUris.withAppendedId(artworkUri, songCursor.getLong(albumCoverId))
                //Try to get the Album cover and catch if fail
                try {
                    var imageInputStream = context.contentResolver.openInputStream(albumArtUri)
                    albumDrawable = Drawable.createFromStream(imageInputStream, albumArtUri.toString())
                } catch (e: FileNotFoundException) {
                    albumDrawable = context.getDrawable(R.drawable.baum)
                }
                //Add the Values to the Array
                music_CoverID.add(albumDrawable)
                music_Duration.add((songCursor.getInt(songDuration)) / 1000 * 60)
                //Get Location of File

                var mediaDescriper = MediaDescriptionCompat.Builder().setMediaId(songCursor.getString(albumCoverId)).setTitle(songCursor.getString(albumTitle)).build()
                MusicFiles.add(mediaDescriper)
                Log.i("ALBUMNAMES", album_Title.toString())



                //Go to the next Cursor Position
            } while (songCursor.moveToNext())

            //Copy values to Compainon Object
            albums = album_Title
            Log.i("MUSICLIBRARY",MusicFiles.toString())



        }


    }


}

0 个答案:

没有答案