SpeechRecognitionService.swift 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 client: Client
  25. var call: Call?
  26. static let sharedInstance = SpeechRecognitionService()
  27. private init() {
  28. fileDescriptorSet = FileDescriptorSet(filename: "speech.out")
  29. client = Client(address:HOST, certificates: nil, host: nil)
  30. }
  31. func streamAudioData(_ audioData: NSData, completion: SpeechRecognitionCompletionHandler) {
  32. if (!nowStreaming) {
  33. // if we aren't already streaming, set up a gRPC connection
  34. call = client.createCall(host: HOST,
  35. method: "/google.cloud.speech.v1beta1.Speech/StreamingRecognize",
  36. timeout: 120.0)
  37. if let call = call {
  38. let metadata = Metadata(["x-goog-api-key":API_KEY,
  39. "x-ios-bundle-identifier":Bundle.main.bundleIdentifier!])
  40. _ = call.start(metadata:metadata)
  41. let recognitionConfig = fileDescriptorSet.createMessage("RecognitionConfig")!
  42. recognitionConfig.addField("encoding", value: 1)
  43. recognitionConfig.addField("sample_rate", value: self.sampleRate)
  44. recognitionConfig.addField("language_code", value: "en-US")
  45. recognitionConfig.addField("max_alternatives", value: 30)
  46. let streamingRecognitionConfig = fileDescriptorSet.createMessage("StreamingRecognitionConfig")!
  47. streamingRecognitionConfig.addField("config", value: recognitionConfig)
  48. streamingRecognitionConfig.addField("single_utterance", value: false)
  49. streamingRecognitionConfig.addField("interim_results", value: true)
  50. let streamingRecognizeRequest = fileDescriptorSet.createMessage("StreamingRecognizeRequest")!
  51. streamingRecognizeRequest.addField("streaming_config", value:streamingRecognitionConfig)
  52. let messageData = streamingRecognizeRequest.data()
  53. call.sendMessage(data:messageData)
  54. nowStreaming = true
  55. self.receiveMessage()
  56. }
  57. }
  58. if let call = call {
  59. let streamingRecognizeRequest = fileDescriptorSet.createMessage("StreamingRecognizeRequest")!
  60. streamingRecognizeRequest.addField("audio_content", value: audioData)
  61. let messageData = streamingRecognizeRequest.data()
  62. call.sendMessage(data:messageData)
  63. }
  64. }
  65. func receiveMessage() {
  66. if let call = call {
  67. _ = call.receiveMessage() {(data) in
  68. if let data = data {
  69. if let responseMessage =
  70. self.fileDescriptorSet.readMessage("StreamingRecognizeResponse", data:data) {
  71. responseMessage.forEachField("results") {(field) in
  72. field.message().forOneField("is_final") {(field2) in
  73. field.message().forOneField("alternatives") {(field3) in
  74. let alternativeMessage = field3.message()
  75. if let transcript = alternativeMessage.oneField("transcript") {
  76. print(transcript.string())
  77. }
  78. }
  79. }
  80. }
  81. }
  82. }
  83. self.receiveMessage()
  84. }
  85. }
  86. }
  87. func stopStreaming() {
  88. if (!nowStreaming) {
  89. return
  90. }
  91. nowStreaming = false
  92. if let call = call {
  93. _ = call.close {}
  94. }
  95. }
  96. func isStreaming() -> Bool {
  97. return nowStreaming
  98. }
  99. }