Core Speech Kit 是一个由 Apple 提供的框架,用于在 iOS 和 macOS 应用中实现语音识别和语音合成功能。它为开发者提供了在应用程序中实现自然语言处理和语音交互的能力。这个框架包括两个主要的组件:
-
语音识别(Speech Recognition):
- 功能:可以将用户的语音输入转换为文本。这对于创建语音驱动的应用程序、语音到文本的功能以及语音搜索等都非常有用。
- API:通过
SFSpeechRecognizer
类来访问语音识别功能。开发者可以使用它来启动语音识别请求并获取识别结果。
-
语音合成(Speech Synthesis):
- 功能:可以将文本转换为语音。这使得应用程序能够“朗读”文本内容,增强无障碍功能或提供更自然的用户交互体验。
- API:通过
AVSpeechSynthesizer
类来实现语音合成功能。开发者可以用它来配置发音、语速、音调等,并播放合成的语音。
Core Speech Kit 的使用需要在应用的 Info.plist 文件中添加相应的权限请求描述,以便获得用户的同意。具体来说,你需要请求“语音识别”权限,并说明应用程序为何需要访问用户的语音数据。
这个框架对于需要语音交互或无障碍功能的应用程序来说是一个非常有用的工具,能够大大提升用户体验。
当然!下面是一个简单的示例,演示如何使用 Core Speech Kit 进行语音识别和语音合成。在这个例子中,我们将实现一个简单的 iOS 应用,能够将用户的语音转换为文本,并朗读给用户听。
首先,你需要在 Xcode 中创建一个新的 iOS 项目,并确保你的项目已经配置好以使用 Core Speech Kit。
1. 配置 Info.plist
在 Info.plist 文件中,添加以下两个权限描述:
<key>NSSpeechRecognitionUsageDescription</key>
<string>我们需要使用语音识别来将您的语音转换为文本。</string>
<key>NSMicrophoneUsageDescription</key>
<string>我们需要使用麦克风来接收您的语音。</string>
2. 实现语音识别和语音合成
在你的 ViewController.swift 文件中,添加以下代码:
import UIKit
import Speech
import AVFoundation
class ViewController: UIViewController, SFSpeechRecognizerDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var startButton: UIButton!
private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
private let audioEngine = AVAudioEngine()
private let speechRecognitionRequest = SFSpeechAudioBufferRecognitionRequest()
private var isRecording = false
override func viewDidLoad() {
super.viewDidLoad()
SFSpeechRecognizer.requestAuthorization { authStatus in
OperationQueue.main.addOperation {
switch authStatus {
case .authorized:
self.startButton.isEnabled = true
case .denied, .restricted, .notDetermined:
self.startButton.isEnabled = false
@unknown default:
fatalError()
}
}
}
}
@IBAction func startButtonTapped(_ sender: UIButton) {
if isRecording {
stopRecording()
} else {
startRecording()
}
}
private func startRecording() {
guard !isRecording else { return }
isRecording = true
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.record, mode: .default, options: .defaultToSpeaker)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
} catch {
print("Audio session setup error: \(error)")
return
}
let inputNode = audioEngine.inputNode
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
self.speechRecognitionRequest.append(buffer)
}
audioEngine.prepare()
do {
try audioEngine.start()
} catch {
print("Audio engine start error: \(error)")
return
}
speechRecognizer.recognitionTask(with: speechRecognitionRequest) { result, error in
if let result = result {
self.textView.text = result.bestTranscription.formattedString
self.speak(text: result.bestTranscription.formattedString)
}
if error != nil {
self.stopRecording()
}
}
}
private func stopRecording() {
audioEngine.stop()
speechRecognitionRequest.endAudio()
audioEngine.inputNode.removeTap(onBus: 0)
isRecording = false
}
private func speak(text: String) {
let utterance = AVSpeechUtterance(string: text)
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(utterance)
}
}
3. 配置用户界面
在你的 Main.storyboard 文件中,添加以下界面组件:
请确保你的设备或模拟器有麦克风权限,并且设备支持语音识别功能。
- 一个
UITextView
用于显示识别的文本。 - 一个
UIButton
用于开始和停止录音,连接到startButtonTapped
方法。 -
总结
上述代码实现了一个简单的 iOS 应用,其中:
- 按下按钮开始录音并进行语音识别。
- 识别到的文本会显示在
UITextView
中,并通过AVSpeechSynthesizer
朗读出来。 - 按下按钮再次可以停止录音。