what3words 语音 API

概述

what3words Swift API 封装器可以将音频中口述的三词地址转换为三词地址建议列表。

身份验证

要使用此库,您需要一个 what3words API 密钥,可以在此处获取。如果您希望使用语音 API 调用,请将语音 API 计划添加到您的帐户

示例

此软件包中提供了一个使用语音 API 的 iOS UIKit 示例:./Examples/VoiceAPI/VoiceAPI.xcodeproj

安装

语音 API 封装器包含在 what3words 的 Swift API 封装器 代码中。安装说明可以在其 README 中找到。

用法

导入

在任何使用 what3words API 的 Swift 文件中,导入

import W3WSwiftApi

初始化

初始化 W3W API 类

let api = What3WordsV3(apiKey: "YourApiKey")
示例

此示例实例化一个 W3WMicrophone,它为 autosuggest(audio:) 提供音频流,并在调用 autosuggest 时开始录音。

// instantiate the API
let api = What3WordsV3(apiKey: "YourApiKey")

// make a microphone
let microphone = W3WMicrophone()

// call autosuggest
api.autosuggest(audio: microphone, language: "en") { suggestions, error in
  for suggestion in suggestions ?? [] {
    print(suggestion.words ?? "no suggestions")
  }
}

W3WMicrophone 类使用设备的麦克风并为 autosuggest(audio:) 提供音频流,当传递 W3WMicrophone 实例时,它将自动调用 microphone.start()

选项

核心 API 调用中可用的相同选项也适用于语音 API 调用,详细信息请参阅 API 文档

示例

围绕特定坐标聚焦结果。

// coords
let coords = CLLocationCoordinate2D(latitude: 51.4243877, longitude: -0.34745)

// make options
let options = W3WOptions().focus(coords)

// call autosuggest
api.autosuggest(audio: microphone, language: "en", options: options) { suggestions, error in
  for suggestion in suggestions ?? [] {
    print(suggestion.words ?? "no suggestions", suggestion.nearestPlace ?? "")
  }
}

语言

使用 availableVoiceLanguages(completion:) 检索当前支持的语言列表

api.availableVoiceLanguages() { languages, error in
  for language in languages ?? [] {
    print(language.code, language.name, language.nativeName)
  }
}

用户反馈

W3WMicrophone 类包含一个 volumeUpdate 闭包,该闭包不时地被调用以提供音频振幅数据,这对于视觉反馈很有用。

public var volumeUpdate: (Double) -> ()

这是使用一个介于 0 和 1 之间的值调用的,指示相对音量。例如,您的代码中可能有类似以下内容

microphone?.volumeUpdate = { volume in 
  yourViewController.updateMicrophoneView(volume: volume)
}

使用自定义音频数据

对于自定义音频数据源(例如,流式音频或定制设备),请使用 W3WAudioStream 并将其传递给 autosuggest(audio: W3WAudioStream)。通过 add(samples:) 发送数据,并在完成时以 endSamples() 结束。

示例
// instantiate the API
let api = What3WordsV3(apiKey: "YourApiKey")

// make the audio stream
let audio = W3WAudioStream(sampleRate: 44100, encoding: .pcm_f32le)

// call autosuggest
api.autosuggest(audio: audio, language: "en") { suggestions, error in
  yourSoundObject.stop()
  for suggestion in suggestions ?? [] {
    print(suggestion.words ?? "no suggestions")
  }
}

// start sending audio data to autosuggest via the audio stream
while (yourSoundObject.isProducingAudio() {
    audio.add(samples: yourSoundObject.getNextSampleSet())
}
audio.endSamples()

替代方法

语音 API 作为 What3WordsV3 的扩展实现,添加了一个额外的 autosuggest(audio:) 函数。如果需要,这允许将语音 API 代码与主 API 函数分离。

如果只需要语音 API,请直接实例化 W3WVoiceApi

let voiceApi = W3WVoiceApi(apiKey: "YourApiKey")

这两个函数是相同的:autosuggest(audio:completion:)availableVoiceLanguages(completion:)