【发布时间】:2021-03-06 20:30:33
【问题描述】:
我在我的应用程序中使用 MediaPlayer 作为服务。我已经实现了静音和取消静音功能,但是当我在两种状态之间切换时音量出现问题:
假设音乐正在以最大音量播放,而您在未静音状态下将音量降低到一半。然后将声音静音,然后再次取消静音。取消静音后我听到的音频明显比我静音前要安静,尽管手机的媒体音量显示两次都相同。
以低音量播放时则相反,而您在未静音状态下提高音量。在这种情况下,取消静音后的音量听起来更大。
最后,当音量设置为 0 然后取消静音时,对音量的任何更改都不会对音频的响度产生任何影响。在这种情况下,音频保持静音,直到我按下静音然后取消静音。
这让我相信当音乐被取消静音时音量的响度会在你改变音量时对音频产生一些影响,但我不确定如何。
当用户取消静音时,我设置音量的方式是使用 AudioManager 和 getStreamVolume 进行流音乐。
代码如下:
主要活动
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
var mService: BackgroundSoundService? = null
var mIsBound: Boolean? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
//button to switch between muted and unmuted
binding.fab.setOnClickListener {
if (mService?.mute == true) {
val currentVolume = mService!!.getVolume()
mService?.mp?.setVolume(currentVolume, currentVolume)
mService?.setMuted(false)
} else if (mService?.mute == false) {
mService?.mp?.setVolume(0f, 0f)
mService?.setMuted(true)
}
}
}
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, iBinder: IBinder) {
val binder = iBinder as MyBinder
mService = binder.service
mIsBound = true
}
override fun onServiceDisconnected(arg0: ComponentName) {
mIsBound = false
}
}
private fun bindService() {
Intent(this, BackgroundSoundService::class.java).also { intent ->
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
}
private fun unbindService() {
Intent(this, BackgroundSoundService::class.java).also {
unbindService(serviceConnection)
}
}
override fun onStart() {
super.onStart()
bindService()
}
override fun onStop() {
super.onStop()
if (mIsBound == true) {
unbindService()
}
}
}
媒体播放器服务
class BackgroundSoundService : Service() {
var mute = false
private val mBinder: IBinder = MyBinder()
inner class MyBinder : Binder() {
val service: BackgroundSoundService
get() = this@BackgroundSoundService
}
var mp: MediaPlayer? = null
override fun onBind(intent: Intent): IBinder {
return mBinder
}
override fun onUnbind(intent: Intent?): Boolean {
mp?.stop()
mp?.release()
return false
}
override fun onCreate() {
super.onCreate()
val currentVolume = getVolume()
mp = MediaPlayer.create(this, R.raw.song)
mp?.isLooping = true
mp?.setVolume(currentVolume, currentVolume)
mp?.start()
}
fun setMuted(boolean: Boolean) {
mute = boolean
}
fun getVolume(): Float {
val audio = getSystemService(Context.AUDIO_SERVICE) as AudioManager
return audio.getStreamVolume(AudioManager.STREAM_MUSIC) / 15f
}
}
任何帮助表示赞赏,
谢谢
【问题讨论】:
标签: android kotlin android-mediaplayer