Mapbox语音
Mapbox语音使您的iOS应用连接到Mapbox语音API。使用Mapbox路线API获取转向指令,并使用多种语言自然地大声读出来。该库专门设计为与MapboxDirections.swift作为Mapbox iOS导航SDK的一部分一起使用。
入门指南
请在您的Carthage Cartfile中指定以下依赖项
github "mapbox/mapbox-speech-swift" ~> 0.0.1
或在您的CocoaPods Podfile中
pod 'MapboxSpeech', '~> 0.0.1'
然后导入 import MapboxSpeech
或 @import MapboxSpeech;
。
使用方法
您需要Mapbox访问令牌才能使用API。如果您已经在使用Mapbox Maps SDK for iOS或macOS SDK,Mapbox语音会自动识别您的访问令牌,只要您将其放置在应用程序的Info.plist文件中 MGLMapboxAccessToken
键。
以下示例都是用Swift(用main.swift
表示)和Objective-C(用main.m
表示)提供的。
基本
主要的语音合成类是SpeechSynthesizer(在Swift中)或MBSpeechSynthesizer(在Objective-C中)。使用您的访问令牌创建一个语音合成器对象
// main.swift
import MapboxSpeech
let speechSynthesizer = SpeechSynthesizer(accessToken: "<#your access token#>")
// main.m
@import MapboxSpeech;
MBSpeechSynthesizer *speechSynthesizer = [[MBSpeechSynthesizer alloc] initWithAccessToken:@"<#your access token#>"];
或者,您可以将访问令牌放在应用程序的Info.plist文件中的MGLMapboxAccessToken
键,然后使用共享的语音合成器对象
// main.swift
let speechSynthesizer = SpeechSynthesizer.shared
// main.m
MBSpeechSynthesizer *speechSynthesizer = [MBSpeechSynthesizer sharedSpeechSynthesizer];
有了路线对象,构建一个SpeechOptions或MBSpeechOptions对象,并将其传递给方法SpeechSynthesizer.audioData(with:completionHandler:)
。
// main.swift
let options = SpeechOptions(text: "hello, my name is Bobby")
speechSynthesizer.audioData(with: options) { (data: Data?, error: NSError?) in
guard error == nil else {
print("Error calculating directions: \(error!)")
return
}
// Do something with the audio!
}
// main.m
MBSpeechOptions *options = [[MBSpeechOptions alloc] initWithText: "hello, my name is Bobby"];
[speechSynthesizer audioDataWithOptions:options completionHandler:^(NSData * _Nullable data,
NSError * _Nullable error) {
if (error) {
NSLog(@"Error synthesizing speech: %@", error);
return;
}
// Do something with the audio!
}];