Skip to content

Instantly share code, notes, and snippets.

View gaelfoppolo's full-sized avatar

Gaël Foppolo gaelfoppolo

View GitHub Profile
import Speech
import UIKit
public class ViewController: UIViewController, SFSpeechRecognizerDelegate {}
private func askForSpeechRecognitionPermissions() {
SFSpeechRecognizer.requestAuthorization { authStatus in
var enabled: Bool = false
var message: String?
switch authStatus {
case .authorized:
enabled = true
private var speechRecognizer: SFSpeechRecognizer!
private var recognitionTask: SFSpeechRecognitionTask?
speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))!
speechRecognizer.delegate = self
public func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
if available {
// e.g. enable record button
} else {
// e.g. disable record button
}
}
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private let audioEngine = AVAudioEngine()
private func startRecording() throws {
// 1
if let recognitionTask = self.recognitionTask {
recognitionTask.cancel()
self.recognitionTask = nil
}
// 2
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryRecord)
@IBAction func recordButtonTapped() {
if audioEngine.isRunning {
audioEngine.stop()
recognitionRequest?.endAudio()
recordButton.isEnabled = false
} else {
try! startRecording()
}
}
private var recognitionRequest: SFSpeechURLRecognitionRequest?
private func startRecording() throws {
if let recognitionTask = recognitionTask {
recognitionTask.cancel()
self.recognitionTask = nil
}
let path = Bundle.main.path(forResource: "your-file", ofType: "mp3")
if let path = path {
let url = URL(fileURLWithPath: path)
recognitionRequest = SFSpeechURLRecognitionRequest(url: url)