How to pause the background music while recording audio in android

后端 未结 2 691
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 17:42

I am developing an audio record application in android. So if any background music is already playing in the device music player, that should be paused before it starts recordin

相关标签:
2条回答
  • 2021-01-28 18:37

    You can stop other applications from playing music, by requesting AudioFocus. When you are granted AudioFocus, other apps stop playing music and then you can play/record as per your needs.

    AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    
    // Request audio focus for playback
    int result = am.requestAudioFocus(focusChangeListener,
    // Use the music stream.
    AudioManager.STREAM_MUSIC,
    // Request permanent focus.
    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    
    
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // other app had stopped playing song now , so you can start recording.
    }
    

    But, there is only one AudioManager. So, Audio focus is assigned to each application that requests it one by one. This means that if another application requests audio focus, your application will lose it. You will be notified of the loss of audio focus through the onAudioFocusChange handler of the Audio Focus Change Listener (afChangeListener) you registered when requesting the audio focus.

     private OnAudioFocusChangeListener focusChangeListener =
          new OnAudioFocusChangeListener() {
                  public void onAudioFocusChange(int focusChange) {
                             AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
                    switch (focusChange) {
    
                           case (AudioManager.AUDIOFOCUS_LOSS) :
                           //Lost focus. Stop recording
                           break;
    
                           case (AudioManager.AUDIOFOCUS_GAIN) :
                           //Gained AudioFocus. Start recording tasks
                           break;
                           default: break;
            }
        }
    };
    
    0 讨论(0)
  • 2021-01-28 18:42

    get audioManager and check

    audioManager.isMusicActive()
    

    if true

    private void toggleNativePlayer(Context context) {
        Intent intent = new Intent("com.android.music.musicservicecommand");
        intent.putExtra("command", "togglepause");
        context.sendBroadcast(intent);
    }
    

    and after you finish recording run this code again to start play musig again

    0 讨论(0)
提交回复
热议问题