> For the complete documentation index, see [llms.txt](https://docs.mapbox.com/android/ja/navigation/v2/llms.txt)

# Voice instructions

The Mapbox Navigation SDK allows you to provide prompt and detailed voice instructions to users of your application. You can use a voice instruction to notify the user of an upcoming turn or announce that a faster route has been detected.

The Navigation SDK uses the [Mapbox Java SDK's](https://docs.mapbox.com/android/ja/java/guides/) `VoiceInstructions` class to hold information that should be announced out loud by the device (for example, the street that the user should stay on for a certain distance).

## Use default voice instructions

There are two steps to play voice instructions in your application: generate an announcement and then play an announcement.

### Create an instance of the speech API

Before you can generate an announcement, you need to instantiate the speech API in your `Activity` or `Fragment`:

**Java**

```java

MapboxSpeechApi speechApi = new MapboxSpeechApi(this, getMapboxAccessTokenFromResources(), Locale.US.toLanguageTag());
```

**Kotlin**

```kt

val speechApi = MapboxSpeechApi(this, getMapboxAccessTokenFromResources(), Locale.US.toLanguageTag())
```

### Create an instance of the voice instructions player

And before you can play an announcement, you need to instantiate the text-to-speech engine in `onCreate` of your `Activity` or `onActivityCreated` of your `Fragment`. Do not use lazy initialization for this class since it takes some time to initialize the system services required for on-device speech synthesis. With lazy initialization there is a high risk that said services will not be available when the first instruction has to be played.

**Java**

```java

MapboxVoiceInstructionsPlayer voiceInstructionsPlayer;

@Override
public void onCreate() {
  // do your initialization here
  voiceInstructionsPlayer = new MapboxVoiceInstructionsPlayer(
    this,
    getMapboxAccessTokenFromResources(),
    Locale.US.toLanguageTag()
  );
}
```

**Kotlin**

```kt

lateinit var voiceInstructionsPlayer: MapboxVoiceInstructionsPlayer

override fun onCreate() {
  // do your initialization here
  voiceInstructionsPlayer = MapboxVoiceInstructionsPlayer(
    this,
    getMapboxAccessTokenFromResources(),
    Locale.US.toLanguageTag()
  )
}
```

### Generate and play an announcement

Start by generating the content of the announcement using [`MapboxSpeechApi`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavui-voice/com.mapbox.navigation.ui.voice.api/-mapbox-speech-api/). `MapboxSpeechApi` accepts a `VoiceInstructions` object and returns a state object that includes the content of the announcement when it is ready or an error and a fallback with the raw announcement.

Then, pass the content of the announcement to [`MapboxVoiceInstructionsPlayer`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavui-voice/com.mapbox.navigation.ui.voice.api/-mapbox-voice-instructions-player/), which will play the announcement aloud. If you provide a synthesized speech MP3, `MapboxVoiceInstructionsPlayer` will use the `VoiceInstructionsFilePlayer` speech player. If not, it will use `VoiceInstructionsTextPlayer`.

The result of invoking [`MapboxSpeechApi#generate`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavui-voice/com.mapbox.navigation.ui.voice.api/-mapbox-speech-api/#%5Bcom.mapbox.navigation.ui.voice.api%2FMapboxSpeechApi%2Fgenerate%2F%23com.mapbox.api.directions.v5.models.VoiceInstructions%23com.mapbox.navigation.ui.base.util.MapboxNavigationConsumer%5Bcom.mapbox.bindgen.Expected%5Bcom.mapbox.navigation.ui.voice.model.SpeechError%2Ccom.mapbox.navigation.ui.voice.model.SpeechValue%5D%5D%2FPointingToDeclaration%2F%5D%2FFunctions%2F-1497156747) is returned as a callback containing either a success in the form of [`SpeechValue`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavui-voice/com.mapbox.navigation.ui.voice.model/-speech-value/) or failure in the form of [`SpeechError`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavui-voice/com.mapbox.navigation.ui.voice.model/-speech-error/).

**Java**

```java

MapboxNavigationConsumer<Expected<SpeechValue, SpeechError>> speechCallback = new MapboxNavigationConsumer<Expected<SpeechValue, SpeechError>>() {
  @Override
  public void accept(Expected<SpeechValue, SpeechError> value) {
    if (value instanceof Expected.Success) {
      // The announcement data obtained (synthesized speech mp3 file from Mapbox's API Voice) is played
      // using MapboxVoiceInstructionsPlayer
      voiceInstructionsPlayer.play(
          ((SpeechValue) ((Expected.Success) value).getValue()).getAnnouncement(),
          voiceInstructionsPlayerCallback
      );
    } else {
      // In case of error, a fallback announcement is returned that can be played
      // using MapboxVoiceInstructionsPlayer
      voiceInstructionsPlayer.play(
          ((SpeechError) ((Expected.Failure) value).getError()).getFallback(),
          voiceInstructionsPlayerCallback
      );
    }
  }
};

VoiceInstructionsObserver voiceInstructionsObserver = voiceInstructions -> {
  // The data obtained must be used to generate the speech announcement
  speechApi.generate(
      voiceInstructions,
      speechCallback
  );
};
```

**Kotlin**

```kt

val speechCallback =
    MapboxNavigationConsumer<Expected<SpeechError, SpeechValue>> { expected ->
        expected.fold(
            { error ->
                // In case of error, a fallback announcement is returned that can be played
                // using [MapboxVoiceInstructionsPlayer]
                voiceInstructionsPlayer.play(
                    error.fallback,
                    voiceInstructionsPlayerCallback
                )
            },
            { value ->
                // The announcement data obtained (synthesized speech mp3 file from Mapbox's API Voice) is played
                // using [MapboxVoiceInstructionsPlayer]
                voiceInstructionsPlayer.play(
                    value.announcement,
                    voiceInstructionsPlayerCallback
                )
            }
        )
    }

val voiceInstructionsObserver =
    VoiceInstructionsObserver { voiceInstructions ->
        // The data obtained must be used to generate the speech announcement
        speechAPI.generate(
            voiceInstructions,
            speechCallback
        )
    }
```

The result of invoking [`MapboxVoiceInstructionsPlayer#play`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavui-voice/com.mapbox.navigation.ui.voice.api/-mapbox-voice-instructions-player/#%5Bcom.mapbox.navigation.ui.voice.api%2FMapboxVoiceInstructionsPlayer%2Fplay%2F%23com.mapbox.navigation.ui.voice.model.SpeechAnnouncement%23com.mapbox.navigation.ui.base.util.MapboxNavigationConsumer%5Bcom.mapbox.navigation.ui.voice.model.SpeechAnnouncement%5D%2FPointingToDeclaration%2F%5D%2FFunctions%2F-1497156747) is returned as a callback containing [`SpeechAnnouncement`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavui-voice/com.mapbox.navigation.ui.voice.model/-speech-announcement/). This can be used to cleanup any associated files generated before:

**Java**

```java

MapboxNavigationConsumer<SpeechAnnouncement> voiceInstructionsPlayerCallback = new MapboxNavigationConsumer<SpeechAnnouncement>() {
  @Override
  public void accept(SpeechAnnouncement value) {
    speechApi.clean(value);
  }
};
```

**Kotlin**

```kt

val voiceInstructionsPlayerCallback =
    MapboxNavigationConsumer<SpeechAnnouncement> { value ->
        // Remove already consumed file to free-up space
        speechAPI.clean(value)
    }
```

### Start and stop receiving voice events

Register a [`VoiceInstructionsObserver`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavigation-core/com.mapbox.navigation.core.trip.session/-voice-instructions-observer/) with [`MapboxNavigation`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavigation-core/com.mapbox.navigation.core/-mapbox-navigation/):

**Java**

```java

mapboxNavigation.registerVoiceInstructionsObserver(voiceInstructionsObserver);
```

**Kotlin**

```kt

mapboxNavigation.registerVoiceInstructionsObserver(voiceInstructionsObserver)
```

Don't forget to unregister the observer, cancel any potential in-flight `MapboxSpeechApi` requests and shutdown `MapboxVoiceInstructionsPlayer` in `onStop` or `onDestroy`:

**Java**

```java

@Override
protected void onDestroy() {
  super.onDestroy();
  mapboxNavigation.unregisterVoiceInstructionsObserver(voiceInstructionsObserver);
  speechApi.cancel();
  voiceInstructionsPlayer.shutdown();
}
```

**Kotlin**

```kt

override fun onDestroy() {
    super.onDestroy()
    mapboxNavigation.unregisterVoiceInstructionsObserver(voiceInstructionsObserver)
    speechApi.cancel()
    voiceInstructionsPlayer.shutdown()
}
```

Also, every time a new route is obtained make sure to cancel any potential in-flight `MapboxSpeechApi` requests and clear the `MapboxVoiceInstructionsPlayer` queue:

**Java**

```java

RoutesObserver routesObserver = result -> {
  speechApi.cancel();
  voiceInstructionsPlayer.clear();
};
```

**Kotlin**

```kt

val routesObserver =
    RoutesObserver { result ->
        // Every time a new route is obtained make sure to cancel the [MapboxSpeechApi] and
        // clear the [MapboxVoiceInstructionsPlayer]
        speechApi.cancel()
        voiceInstructionsPlayer.clear()
    }
```

### Adjust voice instructions volume

To set the volume level of `MapboxVoiceInstructionsPlayer` you need to provide a value between `0.0` (mute) and `1.0` (max) through [`SpeechVolume`](https://docs.mapbox.com/android/navigation/v2/api/2.22.2/libnavui-voice/com.mapbox.navigation.ui.voice.model/-speech-volume/):

**Java**

```java

// This is used to set the speech volume to mute
voiceInstructionsPlayer.volume(new SpeechVolume(0.0f));
```

**Kotlin**

```kt

// This is used to set the speech volume to mute
voiceInstructionsPlayer.volume(SpeechVolume(0.0f))
```