SpeechRecognitionService.swift 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. //
  2. // Copyright 2016 Google Inc. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import Foundation
  17. let API_KEY : String = "YOUR_API_KEY"
  18. let HOST = "speech.googleapis.com"
  19. typealias SpeechRecognitionCompletionHandler = (Any?, NSError?) -> (Void)
  20. class SpeechRecognitionService {
  21. var sampleRate: Int = 16000
  22. private var nowStreaming = false
  23. var fileDescriptorSet : FileDescriptorSet
  24. var channel: Channel
  25. var call: Call?
  26. var completion: SpeechRecognitionCompletionHandler!
  27. static let sharedInstance = SpeechRecognitionService()
  28. private init() {
  29. fileDescriptorSet = FileDescriptorSet(filename: "speech.out")
  30. channel = Channel(address:HOST, certificates: nil, host: nil)
  31. }
  32. func streamAudioData(_ audioData: NSData, completion: @escaping SpeechRecognitionCompletionHandler) {
  33. self.completion = completion
  34. do {
  35. if (!nowStreaming) {
  36. // if we aren't already streaming, set up a gRPC connection
  37. call = channel.makeCall("/google.cloud.speech.v1beta1.Speech/StreamingRecognize")
  38. if let call = call {
  39. let metadata = Metadata(["x-goog-api-key":API_KEY,
  40. "x-ios-bundle-identifier":Bundle.main.bundleIdentifier!])
  41. try call.start(metadata:metadata)
  42. let recognitionConfig = fileDescriptorSet.makeMessage("RecognitionConfig")!
  43. recognitionConfig.addField("encoding", value: 1)
  44. recognitionConfig.addField("sample_rate", value: self.sampleRate)
  45. recognitionConfig.addField("language_code", value: "en-US")
  46. recognitionConfig.addField("max_alternatives", value: 30)
  47. let streamingRecognitionConfig = fileDescriptorSet.makeMessage("StreamingRecognitionConfig")!
  48. streamingRecognitionConfig.addField("config", value: recognitionConfig)
  49. streamingRecognitionConfig.addField("single_utterance", value: false)
  50. streamingRecognitionConfig.addField("interim_results", value: true)
  51. let streamingRecognizeRequest = fileDescriptorSet.makeMessage("StreamingRecognizeRequest")!
  52. streamingRecognizeRequest.addField("streaming_config", value:streamingRecognitionConfig)
  53. let messageData = streamingRecognizeRequest.data()
  54. _ = call.sendMessage(data:messageData)
  55. nowStreaming = true
  56. self.receiveMessage()
  57. }
  58. }
  59. if let call = call {
  60. let streamingRecognizeRequest = fileDescriptorSet.makeMessage("StreamingRecognizeRequest")!
  61. streamingRecognizeRequest.addField("audio_content", value: audioData)
  62. let messageData = streamingRecognizeRequest.data()
  63. let success = call.sendMessage(data:messageData)
  64. if (!success) {
  65. stopStreaming() // restart
  66. }
  67. }
  68. } catch (let error) {
  69. print("Call error: \(error)")
  70. }
  71. }
  72. func receiveMessage() {
  73. do {
  74. if let call = call {
  75. try call.receiveMessage() {(data) in
  76. if let data = data {
  77. if let responseMessage =
  78. self.fileDescriptorSet.readMessage("StreamingRecognizeResponse", data:data) {
  79. self.completion(responseMessage, nil)
  80. }
  81. }
  82. self.receiveMessage()
  83. }
  84. }
  85. } catch (let error) {
  86. print("Receive error: \(error)")
  87. }
  88. }
  89. func stopStreaming() {
  90. if (!nowStreaming) {
  91. return
  92. }
  93. nowStreaming = false
  94. if let call = call {
  95. do {
  96. try call.close {}
  97. } catch (let error) {
  98. print("call error \(error)")
  99. }
  100. }
  101. }
  102. func isStreaming() -> Bool {
  103. return nowStreaming
  104. }
  105. }