9
votes

Comment déterminer quand Google Maps parle sous Android

J'essaie de modifier mon application pour suspendre la lecture audio lorsque Google Maps annonce une direction de virage par virage.

J'ai ajouté le code suivant (illustré ci-dessous) à mon application. L'auditeur de mise au point audio est appelé lorsque des applications telles que Pandora Radio ou Spotify demandent la mise au point audio pour lire de la musique, mais il n'est pas appelé lorsque Google Maps annonce un sens de rotation. Y a-t-il une autre intention que je devrais écouter pour détecter ce comportement?

 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.requestAudioFocus(new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
            .setAudioAttributes(
                    new AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_MEDIA)
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .build()
            )
            .setAcceptsDelayedFocusGain(true)
            .setOnAudioFocusChangeListener(new AudioManager.OnAudioFocusChangeListener() {
                @Override
                public void onAudioFocusChange(int focusChange) {
                    // This is called by Pandora Radio and Spotify
                    Log.d("Focus change:", " Event is: " + focusChange);
                }
            }).build());


2 commentaires

Avez-vous vérifié avec différents AudioAttributes ?


@MorrisonChang J'ai, mais l'auditeur n'est toujours pas appelé.


4 Réponses :



1
votes

Vous aurez besoin des mises à jour AudioPlaybackCallback de AudioManager .

Cela ne fonctionne que sur Android O et supérieur.

Pour ce faire, vous devez accéder au gestionnaire audio -

// Loop through the configs to see the media's usage data
configs.get(0).getAudioAttributes().getUsage();

Et puis ajouter l'auditeur comme ceci -

Handler handler = new Handler();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    audioManager.registerAudioPlaybackCallback(new AudioManager.AudioPlaybackCallback() {
        @Override
        public void onPlaybackConfigChanged(List<AudioPlaybackConfiguration> configs) {
             super.onPlaybackConfigChanged(configs);
            // This will be called when navigation audio state on google maps changes
            Log.d("audio active", String.valueOf(audioManager.isMusicActive()));
        }
    }, handler);
}

La List configs renvoyée dans le rappel a un objet AudioAttribute qui contient une chaîne décrivant la lecture audio. Pour la navigation sur Google Maps, la valeur de la constante String est USAGE_ASSISTANCE_NAVIGATION_GUIDANCE que vous pouvez comparer pour être sûr que c'est Google Maps qui annonce la direction de navigation.

Par programme, vous pouvez l'obtenir comme ceci p>

 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);


0 commentaires

-1
votes
@Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_GAIN:
                if (mPlayOnAudioFocus && !isPlaying()) {
                    play();
                } else if (isPlaying()) {
                    setVolume(MEDIA_VOLUME_DEFAULT);
                }
                mPlayOnAudioFocus = false;
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                setVolume(MEDIA_VOLUME_DUCK);
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                if (isPlaying()) {
                    mPlayOnAudioFocus = true;
                    pause();
                }
                break;
            case AudioManager.AUDIOFOCUS_LOSS:
                mAudioManager.abandonAudioFocus(this);
                mPlayOnAudioFocus = false;
                stop();
                break;
        }
    }
}
The following code snippet contains an implementation of this interface for an app that plays audio. And it handles ducking for transient audio focus loss. It also handles audio focus change due to the user pausing playback, vs another app (like the Google Assistant) causing transient audio focus lossdoes your app temporarily need audio focus (with the option to duck), since it needs to play an audio notification, or a turn by turn spoken direction, or it needs to record audio from the user for a short period of time? This is 
  AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK.
Ducking vs pausing on transient audio focus loss
You can choose to pause playback or temporarily reduce the volume of your audio playback in the OnAudioFocusChangeListener, depending on what UX your app needs to deliver. Android O supports auto ducking, where the system will reduce the volume of your app automatically without you having to write any extra code. In your OnAudioFocusChangeListener, just ignore the AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK event.In Android N and earlier, you have to implement ducking yourself (as shown in the code snippet above).for Detail visit :https://medium.com/androiddevelopers/audio-focus-3-cdc09da9c122AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
added in API level 8
public static final int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
Used to indicate a temporary request of audio focus, anticipated to last a short amount of time, and where it is acceptable for other audio applications to keep playing after having lowered their output level (also referred to as "ducking"). Examples of temporary changes are the playback of driving directions where playback of music in the background is acceptable.

0 commentaires

0
votes

Pour Android O, les notifications de changement de focus du canard de navigation manquantes n'étaient reçues qu'après avoir défini explicitement les attributs audio et le type de contenu de mon lecteur sur la parole (lorsque je lis des fichiers mp3 de podcast, je n'ai pas testé avec d'autres types de contenu): XXX


0 commentaires