Your own voice in the Mapbox Navigation SDK, with the Moses TTS API
Replace the turn-by-turn voice in the Mapbox Navigation SDK for Android and iOS with your own voice: no backend, a scoped key, prefetching and a fallback. Code included.
Turn-by-turn navigation is the one place where an app talks to its users for minutes at a time, and in most apps it does so in the phone’s default voice or the map provider’s. If your brand has a voice, in your app, your ads or your phone line, the navigation should sound the same. This article shows how to replace the voice in the Mapbox Navigation SDK on Android and iOS with a voice from the Moses TTS API, without adding a server, and with the parts that decide whether it works on the road: a scoped key, timing, caching and a fallback.
How Mapbox voice guidance works
When you request a route with voice_instructions=true, the Mapbox Directions API returns, for every step, a list of voiceInstructions. Each one has:
announcement: the plain text, for example “In 300 meters, turn left onto Hauptstraße”;ssmlAnnouncement: the same as SSML, with a slightly faster speaking rate;distanceAlongGeometry: how far before the maneuver it should be spoken.
While the user drives, the SDK decides when an instruction is due and hands it to a speech component, which decides how it sounds. That second part is what we replace. Everything else (rerouting, timing, the banner text) stays with Mapbox.
You can send either version to Moses. The Moses TTS API understands the SSML subset Mapbox uses: Amazon-specific tags such as <amazon:effect> are skipped, <prosody rate> is applied, and street names in <say-as interpret-as="address"> are written out, so “Main St NW” is read as “Main Street Northwest”. The plain announcement is enough in most cases, since Moses reads numbers, distances, units and times as words on its own. The examples below use it.
Three rules for a navigation voice
A voice assistant can afford a short pause before it answers. A navigation instruction can’t: “turn left now” is useless two seconds late. So the design follows three rules:
- Prefetch the route. All instructions are known as soon as the route is. Synthesize them in the background as soon as the route is shown, before the user taps Start (the first instruction is due the moment navigation begins), and again after a reroute. When an instruction comes due, its audio is usually already on the device.
- Cache by text. “Continue for 2 kilometers” and “You have arrived at your destination” repeat constantly. Cache on the device by voice, language and text, and you pay for each phrase once per device.
- Never stay silent. If audio isn’t ready within a short deadline (dead zone, tunnel, a refused request), let the device’s built-in voice speak instead. A different voice is better than a missed turn.
Step 1: the speech request
The standard speech endpoint turns a whole text into a WAV file. It takes an OpenAI-style request and streams the audio back while it is generated, about six times faster than real time:
curl https://moses-ai.com/tts/v1/audio/speech \
-H "Authorization: Bearer $MOSES_TTS_KEY" \
-H "Content-Type: application/json" \
-d '{"input": "In 300 meters, turn left onto Hauptstraße.",
"voice": "alba", "language": "en", "speed": 1.08, "response_format": "wav"}' \
-o turn-left.wav
- Speed. Mapbox’s SSML announcements ask for
<prosody rate="1.08">, so its own voice speaks 8% faster than normal. When you send the plain text, set"speed": 1.08to match (anything from 0.5 to 2.0 works). - Streamed WAV. Because the audio streams while it is generated, the WAV header can’t know the length yet: its two size fields are
0xFFFFFFFF. Many players cope, but some Android versions reject such files, so the code below writes the real sizes once the download is complete. - Loudness. Voices differ in level. In our tests, short callouts peaked anywhere from about −1 to −22 dBFS depending on the voice. Navigation prompts need to cut through road noise, so the code below raises each clip to a common peak (about −1 dBFS, at most 8×) after the download. That costs a few milliseconds and never clips.
Hear the voices and try a key in the live example; every field is in the API reference.
Step 2: a key just for the app
Your app already ships a Mapbox access token: a public token, limited by its scopes, that every installed copy uses to call Mapbox. The Moses key works the same way, and the same discipline applies: assume anything in the app can be extracted, and limit what the key can do.
- Limit the scope to text to speech. In the console under API keys, create a key with only the TTS permission. It can’t transcribe audio or open any other Moses API, whatever someone does with it.
- Give the key its own limits. On the same page, cap what the key can do on its own: text-to-speech characters a day, requests at once and requests a minute. Size them for your real traffic with some headroom. Whoever extracts the key can then use no more than that, and your account’s limits still apply on top. The key also has limits per IP address, which cap what one phone can do with it: 50 requests a minute per address unless you set another number (up to 100). That covers prefetching a typical route, a few dozen announcements, one at a time. Phones on the same Wi-Fi or behind the same mobile carrier address share that budget, so for many users in one place, ask us to raise it.
- One key per app, and nothing else on it. Don’t reuse your server or test keys. A key that exists only in the app can be revoked and replaced on its own, without touching anything else.
- Make it replaceable without a release. Load the key from remote configuration with the built-in key as a fallback, so you can rotate it in minutes.
- Let prepaid credit cap the risk. Moses is prepaid: a misused key can spend at most the credit on the account. Keep the balance in proportion to your traffic, and watch usage in the console for unexpected spikes.
- Keep the key out of source control, just like the Mapbox token: in
local.propertiesor a build secret on Android, in an untracked.xcconfigon iOS.
Allowed websites, the other key restriction in the console, protects keys used in web pages. It doesn’t apply to native apps, which send no website. If you need per-user authentication, per-user limits or a voice that the app can’t change, a small proxy on your own server is the next step. Most navigation apps don’t need one.
An account runs a limited number of speech requests at once, and every installed copy of your app counts toward it. If your app needs more, contact us and we raise the limit for your account. Either way, prefetch one phrase at a time on each device (that also stays within the key’s 50 requests a minute per IP address on all but very long routes), and treat a refused request (HTTP 429 or 503) as “use the device voice now, try again after the Retry-After seconds the answer names”. A refused key (HTTP 401, 402 or 403) won’t start working mid-drive, so stop asking for the rest of the session. The code below does both.
Step 3: Android
On Android, the SDK reports each due instruction to a VoiceInstructionsObserver, and MapboxVoiceInstructionsPlayer plays a SpeechAnnouncement. If the announcement has a file, the player plays that file with a media player, and handles audio focus and the queue for you. If it has no file, it speaks the text with the device’s built-in voice. That gives us the fallback for free. See Mapbox’s voice instructions guide for the default setup this replaces.
Project setup
The code below was tested with Navigation SDK v3 (com.mapbox.navigationcore:voice-ndk27:3.32.1, next to the other navigation modules your app already uses). The key goes into local.properties, which stays out of source control, as moses.apiKey=mk_..., and reaches the code through BuildConfig. Since Android Gradle Plugin 8, BuildConfig is only generated when you switch it on. In app/build.gradle.kts:
import java.util.Properties
val localProperties = Properties().apply {
rootProject.file("local.properties").takeIf { it.exists() }?.inputStream()?.use { load(it) }
}
android {
defaultConfig {
buildConfigField("String", "MOSES_TTS_KEY",
"\"${localProperties.getProperty("moses.apiKey", "")}\"")
}
buildFeatures { buildConfig = true } // off by default since AGP 8
}
dependencies {
implementation("com.mapbox.navigationcore:voice-ndk27:3.32.1")
}
And the network permission in AndroidManifest.xml, if your app doesn’t have it yet:
<uses-permission android:name="android.permission.INTERNET" />
The voice
One class does it all: it fetches and caches the audio, shares a request between playback and prefetching, gives each due instruction a real 1.5-second deadline, backs off when the API says so, and stops cleanly:
import android.content.Context
import android.os.Handler
import android.os.Looper
import com.mapbox.navigation.core.trip.session.VoiceInstructionsObserver
import com.mapbox.navigation.voice.api.MapboxVoiceInstructionsPlayer
import com.mapbox.navigation.voice.model.SpeechAnnouncement
import com.mapbox.navigation.voice.model.SpeechVolume
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.security.MessageDigest
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.abs
import kotlin.math.min
class MosesNavigationVoice(
context: Context,
private val apiKey: String, // a TTS-only key: BuildConfig.MOSES_TTS_KEY
private val voice: String = "alba",
private val language: String = "en",
private val speed: Double = 1.08, // the rate of Mapbox's own voice
private val lexicon: Map<String, String> = emptyMap(), // your own pronunciations
private val deadlineMs: Long = 1500,
) {
private val player = MapboxVoiceInstructionsPlayer(context, language)
private val dir = File(context.cacheDir, "moses-voice").apply { mkdirs() }
private val live = Executors.newSingleThreadExecutor() // due instructions, in order
private val prefetcher = Executors.newSingleThreadExecutor() // walks a route, one phrase at a time
private val network = Executors.newFixedThreadPool(2) // at most 2 requests at once
private val inFlight = HashMap<String, Future<File>>() // text -> its running request
private val main = Handler(Looper.getMainLooper())
private val session = AtomicInteger() // stop() starts a new one, dropping what waits
@Volatile private var pausedUntil = 0L // after 429/503, as long as Retry-After says
@Volatile private var refused = false // after 401/402/403: this key won't work today
init { prefetcher.execute { trimCache(maxBytes = 30L shl 20) } }
val observer = VoiceInstructionsObserver { instruction ->
val text = instruction.announcement() ?: return@VoiceInstructionsObserver
val mine = session.get()
live.execute {
// Cached: at once. Otherwise wait at most deadlineMs; a late download carries on and
// lands in the cache for next time, and this instruction gets the device voice.
val file = runCatching { audio(text).get(deadlineMs, TimeUnit.MILLISECONDS) }.getOrNull()
main.post {
if (session.get() != mine) return@post // navigation stopped meanwhile
player.play(SpeechAnnouncement.Builder(text).file(file).build()) { /* keep the file */ }
}
}
}
fun prefetch(texts: Collection<String>) {
val mine = session.get()
texts.distinct().forEach { text ->
prefetcher.execute {
while (session.get() == mine && !refused && System.currentTimeMillis() < pausedUntil) {
Thread.sleep(500) // backing off: wait, don't skip
}
if (session.get() == mine) runCatching { audio(text).get(15, TimeUnit.SECONDS) }
}
}
}
/** When navigation ends: drop queued callouts and instructions still waiting for audio. */
fun stop() {
session.incrementAndGet()
player.clear()
}
fun volume(level: Float) = player.volume(SpeechVolume(level)) // 0f mutes
fun shutdown() {
stop()
live.shutdownNow(); prefetcher.shutdownNow(); network.shutdownNow()
player.shutdown()
}
/** The audio for a text: from the cache, from a request already running, or a new request. */
private fun audio(text: String): Future<File> {
// "v2" names the processing below: change it and stored files are fetched again
val file = File(dir, sha256("v2|$voice|$language|$speed|$lexicon|$text") + ".wav")
if (file.exists()) {
file.setLastModified(System.currentTimeMillis()) // recently used: keep it
return done { file }
}
if (refused || System.currentTimeMillis() < pausedUntil) return done { throw IOException("not now") }
synchronized(inFlight) {
inFlight[text]?.takeIf { !it.isDone }?.let { return it } // share, never ask twice
return FutureTask { download(text, file) }.also { inFlight[text] = it; network.execute(it) }
}
}
private fun done(result: () -> File): Future<File> = FutureTask(Callable { result() }).apply { run() }
private fun download(text: String, file: File): File {
val body = JSONObject()
.put("input", text).put("voice", voice).put("language", language)
.put("speed", speed).put("response_format", "wav").put("lexicon", JSONObject(lexicon))
val conn = URL("https://moses-ai.com/tts/v1/audio/speech").openConnection() as HttpURLConnection
try {
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 5_000
conn.readTimeout = 10_000
conn.setRequestProperty("Authorization", "Bearer $apiKey")
conn.setRequestProperty("Content-Type", "application/json")
conn.outputStream.use { it.write(body.toString().toByteArray()) }
when (val code = conn.responseCode) {
200 -> Unit
401, 402, 403 -> { refused = true; throw IOException("key refused: $code") }
429, 503 -> {
val seconds = conn.getHeaderField("Retry-After")?.toLongOrNull() ?: 10
pausedUntil = System.currentTimeMillis() + seconds * 1000
throw IOException("busy: $code, retry in $seconds s")
}
else -> throw IOException("Moses TTS answered $code")
}
val wav = finishWav(conn.inputStream.use { it.readBytes() })
val part = File.createTempFile("voice", ".part", dir)
part.writeBytes(wav)
if (!part.renameTo(file)) part.delete()
return file
} finally {
conn.disconnect()
}
}
/** Writes the sizes a streamed WAV leaves open, and raises the speech to about -1 dBFS (at most 8x). */
private fun finishWav(wav: ByteArray): ByteArray {
val buf = ByteBuffer.wrap(wav).order(ByteOrder.LITTLE_ENDIAN)
var pos = 12 // after "RIFF", size, "WAVE"
while (pos + 8 <= wav.size && String(wav, pos, 4, Charsets.US_ASCII) != "data") {
val size = buf.getInt(pos + 4)
if (size < 0) throw IOException("not a WAV file")
pos += 8 + size
}
if (pos + 8 > wav.size) throw IOException("not a WAV file")
val start = pos + 8
val samples = (wav.size - start) / 2
buf.putInt(4, wav.size - 8)
buf.putInt(pos + 4, samples * 2)
var peak = 1
for (i in 0 until samples) peak = maxOf(peak, abs(buf.getShort(start + 2 * i).toInt()))
val gain = min(8.0, 29_200.0 / peak) // 29,200 of 32,767 is -1 dBFS
if (gain > 1.05) for (i in 0 until samples) {
val at = start + 2 * i
buf.putShort(at, (buf.getShort(at) * gain).toInt().coerceIn(-32768, 32767).toShort())
}
return wav
}
/** Keeps the cache under maxBytes, dropping the files used longest ago. */
private fun trimCache(maxBytes: Long) {
var total = 0L
dir.listFiles().orEmpty().sortedByDescending { it.lastModified() }.forEach { f ->
total += f.length()
if (total > maxBytes || f.name.endsWith(".part")) f.delete()
}
}
private fun sha256(s: String) = MessageDigest.getInstance("SHA-256")
.digest(s.toByteArray()).joinToString("") { "%02x".format(it) }
}
Wiring it up
Prefetch twice: when the route is previewed, so the departure instruction (“Head north on Main Street”) is ready the moment the user taps Start, and whenever the active route changes, which covers reroutes. An empty route list means navigation ended:
val voice = MosesNavigationVoice(context, BuildConfig.MOSES_TTS_KEY, voice = "alba", language = "en")
mapboxNavigation.registerVoiceInstructionsObserver(voice.observer)
// 1. Preview: the routes are known before navigation starts
mapboxNavigation.requestRoutes(routeOptions, object : NavigationRouterCallback {
override fun onRoutesReady(routes: List<NavigationRoute>, routerOrigin: String) {
voice.prefetch(routes.first().announcements())
showPreview(routes) // your UI; Start calls setNavigationRoutes(routes)
}
override fun onFailure(reasons: List<RouterFailure>, routeOptions: RouteOptions) {}
override fun onCanceled(routeOptions: RouteOptions, routerOrigin: String) {}
})
// 2. Start, reroutes, and the end of navigation
mapboxNavigation.registerRoutesObserver { result ->
val route = result.navigationRoutes.firstOrNull()
if (route == null) voice.stop() else voice.prefetch(route.announcements())
}
fun NavigationRoute.announcements(): List<String> = directionsRoute.legs().orEmpty()
.flatMap { it.steps().orEmpty() }
.flatMap { it.voiceInstructions().orEmpty() }
.mapNotNull { it.announcement() }
// When the user ends navigation without clearing the routes: voice.stop()
// In onDestroy: unregister the observers, then voice.shutdown()
- Only one voice may speak. If you also use
MapboxAudioGuidanceor the defaultMapboxSpeechApisetup, remove it, or the user hears every instruction twice. - Don’t call
MapboxSpeechApi.cleanon these announcements: it deletes the file, and the file is your cache. The class trims the cache itself, to 30 MB by default, dropping what was used longest ago. - A real deadline.
connectTimeoutandreadTimeoutlimit each step of a request, not the whole of it: a response that keeps trickling in can take longer than either. That is why the deadline isFuture.get(1500, MILLISECONDS), while the download itself may finish in the background. - One request per phrase. Playback and prefetching share running requests, so the same text is never fetched twice at once. That saves money and keeps you inside the account’s requests at once, where a duplicate could push the instruction that is due into a 429.
- Volume. Guidance plays on the media stream on most phones. Mute with
voice.volume(0f). When testing, turn the media volume up: the Android emulator starts at 5 of 15, where short callouts are easy to miss. - Check names such as
NavigationRouterCallbackagainst the SDK version you ship; they have changed between major versions.
Step 4: iOS
In Navigation SDK v3 for iOS, speech is a protocol: SpeechSynthesizing. You pass your own implementation as TTSConfig.custom in the CoreConfig of the MapboxNavigationProvider, as described in Mapbox’s user interface guide. Prefetching is built in: the SDK calls prepareIncomingSpokenInstructions with the instructions that are coming up.
This implementation plays Moses audio when it is ready and hands the instruction to the SDK’s own SystemSpeechSynthesizer when it isn’t, forwarding that synthesizer’s events so the SDK always knows what was spoken:
import AVFoundation
import Combine
import CryptoKit
import MapboxDirections
import MapboxNavigationCore
@MainActor
final class MosesSpeechSynthesizer: NSObject, SpeechSynthesizing, AVAudioPlayerDelegate {
private let apiKey: String
private let voice: String
private let language: String
private let speed: Double
private let lexicon: [String: String]
private let deadline: Duration
private let fallback = SystemSpeechSynthesizer()
private let events = PassthroughSubject<VoiceInstructionEvent, Never>()
private var fallbackEvents: AnyCancellable?
private var player: AVAudioPlayer?
private var current: SpokenInstruction?
private var pending: UUID?
private var cache: [String: Data] = [:]
private var inFlight: [String: Task<Data, Error>] = [:]
private var prefetchQueue: Task<Void, Never>?
private var pausedUntil = Date.distantPast // after 429/503, as long as Retry-After says
private var refused = false // after 401/402/403: this key won't work today
var voiceInstructions: AnyPublisher<VoiceInstructionEvent, Never> { events.eraseToAnyPublisher() }
var muted = false { didSet { fallback.muted = muted; if muted { stopSpeaking() } } }
var volume: VolumeMode = .system { didSet { fallback.volume = volume } }
var isSpeaking: Bool { player?.isPlaying == true || fallback.isSpeaking }
var locale: Locale? = .autoupdatingCurrent { didSet { fallback.locale = locale } }
var managesAudioSession = true { didSet { fallback.managesAudioSession = managesAudioSession } }
init(apiKey: String, voice: String = "alba", language: String = "en", speed: Double = 1.08,
lexicon: [String: String] = [:], deadline: Duration = .milliseconds(1500)) {
self.apiKey = apiKey
self.voice = voice
self.language = language
self.speed = speed
self.lexicon = lexicon
self.deadline = deadline
super.init()
fallbackEvents = fallback.voiceInstructions.sink { [weak self] in self?.events.send($0) }
}
func prepareIncomingSpokenInstructions(_ instructions: [SpokenInstruction], locale: Locale?) {
let texts = instructions.map(\.text)
let previous = prefetchQueue
prefetchQueue = Task { // one request at a time, after the previous batch
await previous?.value
for text in texts { _ = try? await self.audio(for: text).value }
}
}
func speak(_ instruction: SpokenInstruction, during legProgress: RouteLegProgress, locale: Locale?) {
guard !muted else { return }
if let previous = current, isSpeaking {
interruptSpeaking()
events.send(VoiceInstructionEvents.DidInterrupt(
interruptedInstruction: previous, interruptingInstruction: instruction))
}
current = instruction
let token = UUID()
pending = token
let task = audio(for: instruction.text)
Task { // the Moses audio, cached or fetched
let data = try? await task.value
guard pending == token else { return }
pending = nil
if let data, play(data, instruction) { return }
fallback.speak(instruction, during: legProgress, locale: locale)
}
Task { // the deadline: better the device voice than a missed turn
try? await Task.sleep(for: deadline)
guard pending == token else { return }
pending = nil
fallback.speak(instruction, during: legProgress, locale: locale)
}
}
func stopSpeaking() { halt(); fallback.stopSpeaking() }
func interruptSpeaking() { halt(); fallback.interruptSpeaking() }
// MARK: - Playback
private func play(_ data: Data, _ instruction: SpokenInstruction) -> Bool {
do {
if managesAudioSession {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playback, mode: .voicePrompt,
options: [.duckOthers, .interruptSpokenAudioAndMixWithOthers])
try session.setActive(true)
}
let player = try AVAudioPlayer(data: data)
if case .override(let level) = volume { player.volume = level }
player.delegate = self
self.player = player
events.send(VoiceInstructionEvents.WillSpeak(instruction: instruction))
return player.play()
} catch {
return false
}
}
nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
Task { @MainActor in
if let instruction = self.current {
self.events.send(VoiceInstructionEvents.DidSpeak(instruction: instruction))
}
self.halt()
}
}
private func halt() {
pending = nil
player?.stop()
player = nil
if managesAudioSession {
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
}
}
// MARK: - Fetching and caching
private struct SpeechRequest: Encodable {
let input: String, voice: String, language: String, speed: Double, lexicon: [String: String]
let response_format = "wav"
}
private func audio(for text: String) -> Task<Data, Error> {
let key = SHA256.hash(data: Data("v2|\(voice)|\(language)|\(speed)|\(text)".utf8))
.map { String(format: "%02x", $0) }.joined()
if let data = cache[key] { return Task { data } }
if let task = inFlight[key] { return task }
if refused || Date() < pausedUntil { return Task { throw URLError(.cannotConnectToHost) } }
var request = URLRequest(url: URL(string: "https://moses-ai.com/tts/v1/audio/speech")!,
timeoutInterval: 10)
request.httpMethod = "POST"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONEncoder().encode(
SpeechRequest(input: text, voice: voice, language: language, speed: speed, lexicon: lexicon))
let task = Task { () throws -> Data in
let (data, response) = try await URLSession.shared.data(for: request)
let http = response as? HTTPURLResponse
switch http?.statusCode {
case 200: return Self.finishWav(data)
case 401, 402, 403: refused = true
case 429, 503:
let seconds = Double(http?.value(forHTTPHeaderField: "Retry-After") ?? "") ?? 10
pausedUntil = Date().addingTimeInterval(seconds)
default: break
}
throw URLError(.badServerResponse)
}
inFlight[key] = task
Task {
if let data = try? await task.value { cache[key] = data }
inFlight[key] = nil
}
return task
}
/// Writes the sizes a streamed WAV leaves open, and raises the speech to about -1 dBFS (at most 8x).
private static func finishWav(_ input: Data) -> Data {
var wav = [UInt8](input)
func u32(_ i: Int) -> Int { (0..<4).reduce(0) { $0 | Int(wav[i + $1]) << (8 * $1) } }
func put32(_ i: Int, _ v: Int) { for k in 0..<4 { wav[i + k] = UInt8((v >> (8 * k)) & 0xff) } }
var pos = 12 // after "RIFF", size, "WAVE"
while pos + 8 <= wav.count, String(bytes: wav[pos..<pos + 4], encoding: .ascii) != "data" {
pos += 8 + u32(pos + 4)
}
guard pos + 8 <= wav.count else { return input }
let start = pos + 8, samples = (wav.count - start) / 2
put32(4, wav.count - 8)
put32(pos + 4, samples * 2)
func sample(_ n: Int) -> Int {
Int(Int16(bitPattern: UInt16(wav[start + 2 * n]) | UInt16(wav[start + 2 * n + 1]) << 8))
}
let peak = max(1, (0..<samples).map { abs(sample($0)) }.max() ?? 1)
let gain = min(8.0, 29_200.0 / Double(peak)) // 29,200 of 32,767 is -1 dBFS
if gain > 1.05 {
for n in 0..<samples {
let v = UInt16(bitPattern: Int16(clamping: Int(Double(sample(n)) * gain)))
wav[start + 2 * n] = UInt8(v & 0xff)
wav[start + 2 * n + 1] = UInt8(v >> 8)
}
}
return Data(wav)
}
}
Then hand it to the navigation provider, exactly where Mapbox’s guide puts a custom synthesizer. The key comes from Info.plist, filled from an untracked .xcconfig, the same way as the Mapbox token:
let key = Bundle.main.object(forInfoDictionaryKey: "MosesTTSKey") as! String
let moses = MosesSpeechSynthesizer(apiKey: key, voice: "alba", language: "en")
let provider = MapboxNavigationProvider(
coreConfig: .init(ttsConfig: .custom(speechSynthesizer: moses))
)
let navigationOptions = NavigationOptions(
mapboxNavigation: provider.mapboxNavigation,
voiceController: provider.routeVoiceController,
eventsManager: provider.eventsManager()
)
let navigationViewController = NavigationViewController(
navigationRoutes: navigationRoutes,
navigationOptions: navigationOptions
)
- Audio session. The code ducks music while it speaks and pauses spoken audio such as podcasts. If your app manages the audio session itself, set
managesAudioSession = false. - Background audio. For guidance with the screen off, enable the Audio background mode, as for the default voice.
- Memory. The in-memory cache holds one route’s phrases, typically well under 10 MB. For long trips, store the WAV files in the caches directory instead, trimmed to a size limit as in the Android code.
- Backing off. While the API asks you to wait (429 or 503 with
Retry-After), new requests fail at once and the device voice speaks. Phrases skipped meanwhile are fetched on the SDK’s next call toprepareIncomingSpokenInstructions. A refused key stops all requests for the session.
The code above is written against Navigation SDK v3. In v2 the same idea works, but a custom synthesizer is set up through RouteVoiceController; see Mapbox’s custom voice controller example. Check names against the API reference for the version you ship.
Choosing the voice, and getting street names right
- Voices. 21 built-in English voices, plus voices for German, French, Italian, Portuguese, Spanish and Dutch. Request the route in the same language with the Directions API’s
languageparameter, and pass that language to Moses. - Your brand voice. Record or upload 10 to 20 seconds of a speaker in the TTS Studio, with their consent, and use
"voice": "clone:<name>". A cloned voice speaks every supported language. - Units. Set
voice_units=metricorimperialon the route request. Moses reads “300 m”, “0.5 mi” and “2:30 pm” as words. - Pronunciation. Street and place names are where any voice stumbles. The
lexiconfield takes your own pronunciations, such as{"Gloucester Road": "Gloster Road"}. Keep the list in remote configuration, so fixes reach users without a release, and add to it when testers report a mistake. - Foreign names. A German street name in an English sentence can be wrapped in a language tag in the input, so it is read the German way.
What it costs
Moses TTS is billed per character spoken, prepaid, with a free trial credit; see pricing. A typical 30-minute drive has a few dozen announcements of about 60 characters, so around 2,000 characters, roughly one cent at the standard price. Phrases cached on the device, such as “Continue for 2 kilometers”, are paid for once and then replayed for free, so regular routes like the daily commute get cheaper over time.
Testing before you ship
- Simulate a route with the SDK’s route simulation and listen to the whole drive once, at real speed, with the media volume turned up (the emulator starts at 5 of 15).
- Start right after the preview, on a fresh install with an empty cache. The first instruction must already be in your voice; if it comes in the device voice, the preview prefetch isn’t wired up.
- Turn on flight mode mid-route. Prefetched instructions should still play in your voice; new ones (after a reroute) should come in the device voice, and none should be skipped.
- Revoke the key, or set its requests a minute to 1, in the console during a test drive. Guidance must carry on in the device voice.
- Reroute often. Take wrong turns in the simulation and check that the new route’s first instruction isn’t late.
- End navigation mid-route, just before a callout is due. Nothing may be spoken after the user has stopped.
- Play music and a podcast at the same time, and check that both duck or pause and come back.
- Collect pronunciation mistakes for your cities and fix them in the lexicon, not in the code.
Your navigation voice doesn’t need to be fast, it needs to be on time. With the route prefetched, a cache on the device, a key that can only speak within its limits, and the device voice as a safety net, it is, and it sounds like you.
Frequently asked questions
Can I use my own text-to-speech voice with the Mapbox Navigation SDK?
Yes. On Android you register a VoiceInstructionsObserver and play your own audio through MapboxVoiceInstructionsPlayer by giving each SpeechAnnouncement a file. On iOS (Navigation SDK v3) you implement the SpeechSynthesizing protocol and pass it as TTSConfig.custom in the CoreConfig of the MapboxNavigationProvider.
Do I need a backend server to use the Moses TTS API from a mobile app?
No. Like the Mapbox access token, a Moses API key can ship in the app. Create a key just for the app with only the text-to-speech permission, so it can't be used for anything else. Give it its own limits (characters a day, requests at once, requests a minute), and revoke and replace it on its own if it leaks. Prepaid credit caps what a leaked key could cost. A proxy is only worth it if you need per-user authentication or limits.
Should I send Mapbox's plain or SSML announcement to the TTS API?
Either works. The Moses TTS API understands the SSML subset Mapbox's announcements use: Amazon-specific tags are skipped, and the speaking rate is applied. The plain announcement is enough in most cases, because Moses reads numbers, distances and units as words on its own.
Won't a network TTS call make turn instructions late?
Not if you prefetch. A Mapbox route contains all its voice instructions when it is created, so you can synthesize them in the background before they are needed and play them from a cache. For the rare instruction that isn't ready in time, fall back to the device's built-in voice after a short deadline.
How much does a custom navigation voice cost with Moses?
Moses TTS is billed per character. A typical route has a few dozen announcements of about 60 characters each, so around 2,000 characters, roughly one cent at the standard price. Phrases cached on the device are not paid for again.
Can the navigation voice be a cloned brand voice?
Yes. Record or upload 10 to 20 seconds of the speaker in the Moses TTS Studio, with their consent, and use the voice as clone:<name>. The same voice can speak every supported language.
Try the realtime voice APIs
Streaming speech to text and text to speech for voice agents, hosted in Germany, with no audio stored. Try both in your browser with an API key.
Open the live example