kotlin Android媒体播放器2分钟后停止播放(前台服务中)

qxgroojn  于 2022-12-13  发布在  Kotlin
关注(0)|答案(1)|浏览(191)

我正在尝试实现媒体播放器,但它在播放2分钟后停止-就像它不在前台服务中一样。前台服务从片段开始,它应该只在创建片段时才存在。
有人能帮忙吗?
服务项目:

class MediaPlayerForegroundService : Service()  {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(1, notificationToDisplayServiceInform(), FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)

        lockCpu()

        fileName = intent?.getStringExtra("fileName")

        handler = Looper.myLooper()?.let { Handler(it) }

        player = MediaPlayer().apply {
            setWakeMode(applicationContext, PowerManager.PARTIAL_WAKE_LOCK)
        }

        player!!.setScreenOnWhilePlaying(true)

        val afd: AssetFileDescriptor = applicationContext.assets.openFd(fileName!!)
        player!!.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length);
        afd.close()

        player!!.setOnPreparedListener {
            handler!!.postDelayed(runnableCheck!!, 200)
        }

        player!!.prepareAsync()

        return START_REDELIVER_INTENT
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                channelId,
                "Foreground Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(
                NotificationManager::class.java
            )
            manager.createNotificationChannel(serviceChannel)
        }
    }

    private fun notificationToDisplayServiceInform(): Notification {
        createNotificationChannel()
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0, notificationIntent, PendingIntent.FLAG_MUTABLE
        )
        return NotificationCompat.Builder(this, channelId)
            .setContentTitle("Simple Foreground Service")
            .setContentText("Explain about the service")
            .setSmallIcon(R.drawable.player_play)
            .setContentIntent(pendingIntent)
            .build()
    }

    private fun lockCpu() {
        wakeLock =
            (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
                newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Movapp::WakeLockFairyTale").apply {
                    acquire()
                }
            }
    }

}

片段代码:

class PlayerFragment : Fragment() {

    private fun startMediaPlayerService(fileName: String){
        Intent(context, MediaPlayerForegroundService::class.java).also {
            it.putExtra("fileName", fileName)
        }.also {
            context!!.startForegroundService(it)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
...
....
        startMediaPlayerService("stories/${slug}/${langPair.to.langCode}.mp3")

        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()

        stopMediaPlayerService()

        _binding = null
    }
}

AndroidManifest.xml:

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

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

    <application
        <service android:name=".MediaPlayerForegroundService"
            android:foregroundServiceType="mediaPlayback"
            android:enabled="true"
            android:exported="false"
            />
    </application>

</manifest>

我试了很多谷歌搜索,读了几篇文章,我不知道为什么它在两分钟后就停止了。我的Android是版本13。在模拟器中,它可以工作。如果我设置player.isLooping = true,它会循环播放2分钟,这意味着服务寿命。

**EDITED:**我想我更接近了。问题似乎出在:

val afd: AssetFileDescriptor = applicationContext.assets.openFd(fileName!!)
        player!!.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length);
        afd.close()

afd.length似乎不正确。afd.declaredLength也太短(相同)。这种情况发生在多个文件中。
我还是不知道怎么修。

**EDITED 2:**2分钟限制的问题似乎只适用于比特率低于96 kbps的mp3文件。我也可以说.ogg文件工作正常。根据文档,规范:支持Mono/Stereo 8-320Kbps constant (CBR) or variable bit-rate (VBR)。这是一个错误吗?

mhd8tkvw

mhd8tkvw1#

有可能这是一个bug。你在Pixel设备上遇到过这个问题吗?我见过一些Pixel设备在其他手机上工作正常的时候有这种行为。

相关问题