How to record speech to text and then play
1 2 3 4 |
First of all, add "Privacy - Microphone Usage Description" line and "Privacy - Speech Recognition Usage Description" line to Info.plist file as follows: |
Then copy and past the following code to your project
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
// // Speech.swift // SpeechToText // // Created by Inventlinks on 15-09-2019. // Copyright © 2019 Inventlinks. All rights reserved. // import UIKit import Speech import AVFoundation class ViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var recordDisplay: UIButton! @IBOutlet weak var playDisplay: UIButton! @IBOutlet weak var textView: UITextView! // Audio section var file:Int = 0 var AudioPlayer:AVAudioPlayer! var AudioSession:AVAudioSession! var AudioRecorder:AVAudioRecorder! // Speech to Text section var lang: String = "en-US" var SpeechRecognitionTask: SFSpeechRecognitionTask? var RecognitionRequest: SFSpeechAudioBufferRecognitionRequest? var AudioEngine = AVAudioEngine() var SpeechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US")) override func viewDidLoad() { super.viewDidLoad() // Initialize AudioSession AudioSession = AVAudioSession.sharedInstance() // to solve 'required condition is false: IsFormatSampleRateAndChannelCountValid(format)' do { try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: []) try AVAudioSession.sharedInstance().setActive(true) } catch { print(error) } // To get permission from user AVAudioSession.sharedInstance().requestRecordPermission{(hasPermission) in if hasPermission { self.textView.text = "Ready to speak?" } } // To check any saved file? if let number:Int = UserDefaults.standard.object(forKey: "recording") as? Int { file = number } // Speech to Text Section recordDisplay.isEnabled = false SpeechRecognizer?.delegate = self as? SFSpeechRecognizerDelegate SpeechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: lang)) SFSpeechRecognizer.requestAuthorization { (authStatus) in var isButtonEnabled = false switch authStatus { case .authorized: isButtonEnabled = true case .restricted: isButtonEnabled = false print("Restricted") case .notDetermined: isButtonEnabled = false print("notdetermined") case .denied: isButtonEnabled = false print("Access denied") @unknown default: break // ... } OperationQueue.main.addOperation() { self.recordDisplay.isEnabled = isButtonEnabled } } } // Audio Section Function that gets path to directory func getDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentDirectory = paths[0] return documentDirectory } @IBAction func englishBTN(_ sender: Any) { lang = "en-US" SpeechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: lang)) textView.text = "Ready to speak?" } @IBAction func japaneseBTN(_ sender: Any) { lang = "ja-JP" SpeechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: lang)) textView.text = "Ready to speak?" } @IBAction func recordBTN(_ sender: Any) { // Speech To Text section SpeechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: lang)) if AudioEngine.isRunning { self.AudioEngine.stop() self.RecognitionRequest?.endAudio() } else { startSpeechRecording() } startAudioRecording() } func startAudioRecording() { // Audio Section: If active file saved? if AudioRecorder == nil{ file = 1 let filename = getDirectory().appendingPathComponent("\(file).m4a") let settings = [AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue] // Start audio recording do{ AudioRecorder = try AVAudioRecorder(url: filename, settings: settings) AudioRecorder.delegate = self AudioRecorder.record() recordDisplay.setTitle("STOP", for: .normal) print("recording now") } catch { showAlert(title: "Error", message: "Please try again") } } else{ // Stopping audio recording AudioRecorder.stop() AudioRecorder = nil // To save recording UserDefaults.standard.set(file, forKey: "recording") recordDisplay.setTitle("Start", for: .normal) // Starting playing let path = getDirectory().appendingPathComponent("\(file).m4a") print("file\(file)") do { AudioPlayer = try AVAudioPlayer(contentsOf: path) AudioPlayer.play() // Only play once AudioPlayer?.numberOfLoops = 0 // Set the volume of playback here. AudioPlayer?.volume = 10.0 print("playing now") } catch { showAlert(title: "Error", message: "Please try again") } } } func startSpeechRecording() { // Cancel the previous task if it's running. if SpeechRecognitionTask != nil { SpeechRecognitionTask?.cancel() SpeechRecognitionTask = nil } RecognitionRequest = SFSpeechAudioBufferRecognitionRequest() let inputNode = AudioEngine.inputNode guard let RecognitionRequest = RecognitionRequest else { fatalError("Error in Recognition") } RecognitionRequest.shouldReportPartialResults = true SpeechRecognitionTask = SpeechRecognizer?.recognitionTask(with: RecognitionRequest, resultHandler: { (result, error) in var FinalResult = false if result != nil { self.textView.text = result?.bestTranscription.formattedString FinalResult = (result?.isFinal)! } if error != nil || FinalResult { self.RecognitionRequest = nil self.SpeechRecognitionTask = nil self.AudioEngine.stop() inputNode.removeTap(onBus: 0) self.recordDisplay.isEnabled = true } }) let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in self.RecognitionRequest?.append(buffer) } AudioEngine.prepare() do { try AudioEngine.start() } catch { print("AudioEngine didn't initialize") } } func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) { if available { recordDisplay.isEnabled = true } else { recordDisplay.isEnabled = false } } @IBAction func playBTN(_ sender: Any) { let path = getDirectory().appendingPathComponent("\(file).m4a") do { AudioPlayer = try AVAudioPlayer(contentsOf: path) AudioPlayer.play() // Only play once AudioPlayer?.numberOfLoops = 0 // Set the volume of playback here. AudioPlayer?.volume = 10.0 print("play button pressed now") } catch { showAlert(title: "Error", message: "Please try again") } } // To display Alert Message func showAlert(title:String, message:String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } } } |