Я успешно внедрил SFSpeechRecognizer в мое приложение ios. теперь я хочу остановить распознаватель кнопкой и перезапустить его.
if(engine.isRunning){
mainbutton.setTitle("start", for: .normal)
print("iwasrunning")
engine.stop()
request.endAudio()
let inputNode = engine.inputNode
let bus = 0
inputNode.removeTap(onBus: bus)
self.engine.stop()
}else{
// Install tap to audio engine input node
mainbutton.setTitle("stop", for: .normal)
print("engine starting...")
// Prepare and start audio engine
engine.prepare()
do {
try engine.start()
} catch {
return print(error)
}
}
С моим текущим кодом я могу получить результаты только в первый раз при запуске приложения, в следующий раз SFSpeechRecognizer не запустится.
Вот полный код для более подробной информации.
import UIKit
import Speech
class ViewController: UIViewController {
@IBOutlet var buttonstart:UIButton!
@IBOutlet var speechtext:UILabel!
@IBOutlet weak var mainbutton: UIButton!
private var recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))
private var request = SFSpeechAudioBufferRecognitionRequest()
private let engine = AVAudioEngine()
override func viewDidLoad() {
super.viewDidLoad()
requestPermissions()
}
@IBAction func startEngine(){
if(engine.isRunning){
mainbutton.setTitle("start", for: .normal)
print("iwasrunning")
engine.stop()
request.endAudio()
let inputNode = engine.inputNode
let bus = 0
inputNode.removeTap(onBus: bus)
self.engine.stop()
}else{
// Install tap to audio engine input node
mainbutton.setTitle("stop", for: .normal)
print("engine starting...")
// Prepare and start audio engine
engine.prepare()
do {
try engine.start()
} catch {
return print(error)
}
}
}
private func requestPermissions() {
// Request recording permission
AVAudioSession.sharedInstance().requestRecordPermission { allowed in
if allowed {
// Request speech recognition authorization
SFSpeechRecognizer.requestAuthorization { status in
switch status {
case .authorized: self.prepareSpeechRecognition()
case .notDetermined, .denied, .restricted: print("SFSpeechRecognizer authorization status: \(status).")
}
}
} else {
print("AVAudioSession record permission: \(allowed).")
}
}
}
private func prepareSpeechRecognition() {
// Check if recognizer is available (has failable initializer)
guard let recognizer = recognizer else {
print("SFSpeechRecognizer not supported.")
return
}
// Prepare recognition task
recognizer.recognitionTask(with: request) { (result, error) in
var isFinal = false
if let result = result {
isFinal = result.isFinal
if(isFinal){
self.mainbutton.setTitle("start", for: .normal)
print("SFSpeechRecognizer result: \(result.bestTranscription.formattedString)")
}
} else {
print("SFSpeechRecognizer error: \(String(describing: error))")
}
}
let inputNode = engine.inputNode
let busNumber = 0
let recordingFormat = inputNode.outputFormat(forBus: busNumber)
inputNode.installTap(onBus: busNumber, bufferSize: 1, format: recordingFormat) {
buffer,
time
in
self.request.append(buffer);
}
}
}