播放和暂停音频时不执行OnAudioFocusChangeListener?

时间:2012-06-18 11:02:29

标签: android audio android-mediarecorder

我正在开发一个应用程序,我需要捕获正在播放的音频。所以我在我的活动中实现了OnAudioFocusChangeListener来监听任何音频变化。但是,当播放或暂停音乐时,听众不会被叫到。以下是我的代码

public class AudioManagerExample extends Activity implements OnAudioFocusChangeListener{
  AudioReceiver adreceiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    AudioManager am =   (AudioManager) getSystemService(AUDIO_SERVICE);

}

@Override
public void onAudioFocusChange(int focusChange) {
    Log.d("AudioManager", "Inside on audio focus change");
}

}

我哪里错了?有没有其他方法可以做到这一点?

由于

普什帕

2 个答案:

答案 0 :(得分:1)

你忘了包含

 am.requestAudioFocus(this,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);

将您的代码更改为

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
am.requestAudioFocus(this,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);

答案 1 :(得分:0)

    private fun initOnAudioFocusChangeListener() {
    val afChangeListener: AudioManager.OnAudioFocusChangeListener =
        AudioManager.OnAudioFocusChangeListener { focusChange ->
            when (focusChange) {
                AudioManager.AUDIOFOCUS_GAIN -> {
                    viewModel.isAppLostAudioFocusLiveData.value = false
                }
                else -> {
                    viewModel.isAppLostAudioFocusLiveData.value = true
                }
            }
        }

    val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        audioManager.requestAudioFocus(
            AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                .setOnAudioFocusChangeListener(afChangeListener).build()
        )
    } else {
        audioManager.requestAudioFocus(
            afChangeListener,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN
        )
    }
}