1

我正在开发一个应用程序,我需要在其中捕获正在播放的音频。所以我在我的活动中实现了 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");
}

}

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

谢谢

普什帕

4

2 回答 2

4

你忘了包括

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

将您的代码更改为

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
am.requestAudioFocus(this,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
于 2012-06-18T11:14:05.343 回答
1
    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
        )
    }
}

于 2020-09-10T15:32:11.573 回答