0

我正在尝试从有线/蓝牙耳机接收媒体按钮事件

我在 MediaSessionCallback 的 onMediaButtonEvent(mediaButtonEvent: Intent?) 方法上接收媒体按钮事件,但音乐播放没有任何反应。

这是我的 MediaPlayerService

private const val LOG_TAG = "LOG_TAG"
private const val MY_EMPTY_MEDIA_ROOT_ID = "empty_root_id"
private const val AUDIO_URL_1 = "https://www.listennotes.com/e/p/94051189e660408b861be9ee28f17f06/"

class MediaPlaybackService : MediaBrowserServiceCompat() {

    private val TAG = "MediaPlaybackService"
    private lateinit var context: Context
    private lateinit var mediaSession: MediaSessionCompat
    private lateinit var stateBuilder: PlaybackStateCompat.Builder
    private lateinit var exoPlayer: SimpleExoPlayer
    private lateinit var dataSourceFactory: DefaultDataSourceFactory
    private val audioAttributes = AudioAttributes.Builder()
        .setContentType(C.CONTENT_TYPE_MUSIC)
        .setUsage(C.USAGE_MEDIA)
        .build()

    override fun onCreate() {
        super.onCreate()
        context = this
        initExoPlayer()
        initDataSourceFactory()
        initMediaSession()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "onStartCommand ${intent?.getParcelableExtra<KeyEvent>                         
                  (Intent.EXTRA_KEY_EVENT)?.keyCode}")
        MediaButtonReceiver.handleIntent(mediaSession, intent)
        return super.onStartCommand(intent, flags, startId)
    }

    private fun initExoPlayer() {
        exoPlayer = ExoPlayerFactory.newSimpleInstance(context)
        exoPlayer.setAudioAttributes(audioAttributes, true)
    }

    private fun initDataSourceFactory() {
        val httpDataSourceFactory = DefaultHttpDataSourceFactory(
            Util.getUserAgent(context, "media-player"),
            null,
            DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
            DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,
            true
        )
        dataSourceFactory = DefaultDataSourceFactory(context, null, httpDataSourceFactory)
    }

    private fun initMediaSession() {
        mediaSession = MediaSessionCompat(context, LOG_TAG).apply {
            setFlags(
                MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                    or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
            )
            stateBuilder = PlaybackStateCompat.Builder()
                .setActions(
                    PlaybackStateCompat.ACTION_PLAY_PAUSE
                        or PlaybackStateCompat.ACTION_PLAY
                        or PlaybackStateCompat.ACTION_PAUSE
                        or PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                        or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
                )
            setPlaybackState(stateBuilder.build())
            setCallback(mediaSessionCallback())
            setSessionToken(sessionToken)
            isActive = true
        }
    }

        private fun mediaSessionCallback() = object : MediaSessionCompat.Callback() {
        override fun onPlay() {
            super.onPlay()
            play()
        }

        override fun onPause() {
            super.onPause()
            pause()
        }

        override fun onSkipToNext() {
            super.onSkipToNext()
            skipToNext()
        }

        override fun onSkipToPrevious() {
            super.onSkipToPrevious()
            skipToPrevious()
        }

        override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {
            Log.i(TAG, "MediaButtonEvent: ${mediaButtonEvent?.getParcelableExtra<KeyEvent> 
                  (Intent.EXTRA_KEY_EVENT)?.keyCode}")
            return super.onMediaButtonEvent(mediaButtonEvent)
        }
    }

    fun play() {
        Log.i(TAG, "Playback State: Playing")
        if (mediaSession.controller.playbackState.state != PlaybackStateCompat.STATE_PAUSED) {
            val mediaSource = getMediaSource(AUDIO_URL_1)
            exoPlayer.prepare(mediaSource)
        }
        setPlaybackState(PlaybackStateCompat.STATE_PLAYING)
        exoPlayer.playWhenReady = true
        setMediaMetadata(title = "Episode 131: Bourne Wild")
    }

    fun pause() {
        Log.i(TAG, "Playback State: Paused")
        setPlaybackState(PlaybackStateCompat.STATE_PAUSED)
        exoPlayer.playWhenReady = false
    }

    fun skipToNext() {
        if (exoPlayer.hasNext()) {
            Log.i(TAG, "ExoPLayer: Skip to Next")
            exoPlayer.next()
        }
    }

    fun skipToPrevious() {
        if (exoPlayer.hasPrevious()) {
            Log.i(TAG, "ExoPLayer: Skip to Previous")
            exoPlayer.previous()
        }
    }
    override fun onLoadChildren(parentId: String, result:     
         Result<MutableList<MediaBrowserCompat.MediaItem>>) {
         result.sendResult(null)
     }

     override fun onGetRoot(lientPackageName: String, clientUid: Int,      
              rootHints: Bundle?): BrowserRoot? {
         return BrowserRoot(MY_EMPTY_MEDIA_ROOT_ID, null)
     }

     override fun onDestroy() {
         exoPlayer.release()
         mediaSession.run {
             isActive = false
             release()
          }
         super.onDestroy()
     }
}

这是我的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.media_player">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:usesCleartextTraffic="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MediaPlaybackService">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </service>

        <receiver android:name="androidx.media.session.MediaButtonReceiver">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

看起来我错过了一些东西,经过多天的挣扎,我找不到问题所在。任何帮助将不胜感激谢谢

4

0 回答 0