我在我的应用中使用 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
}
}
感谢任何帮助,
谢谢
答案 0 :(得分:0)
我最终通过更改服务中 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()
}
老实说,我不明白为什么会这样,所以如果你知道一种更有意义的方法或者可以向我解释这一点,我将不胜感激。
谢谢