我在我的应用程序中使用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()
}
}
}
<<p>媒体播放器服务/strong>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
}
}
感谢任何帮助,
感谢我最终通过改变我的服务中的getVolume函数中的代码来让它工作:
fun getVolume(): Float {
val audio = getSystemService(Context.AUDIO_SERVICE) as AudioManager
val currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC)/ 15f
//just added the following line
return (ln(15 - currentVolume) / ln(15.0)).toFloat()
}
老实说,我不明白为什么这样做,所以如果你知道一个更有意义的方法,或者可以向我解释一下,我会很感激的。
感谢