AudioStreamManager.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. /*
  2. * Copyright 2020, gRPC Authors 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. // NOTE: Implementation based off of Google's for Audio Streaming:
  17. // https://github.com/GoogleCloudPlatform/ios-docs-samples/blob/master/speech/Swift/Speech-gRPC-Streaming/Speech/AudioController.swift
  18. import Foundation
  19. import AVFoundation
  20. enum AudioStreamError: Error {
  21. case failedToConfigure
  22. case failedToFindAudioComponent
  23. case failedToFindMicrophoneUnit
  24. }
  25. protocol StreamDelegate: AnyObject {
  26. func processAudio(_ data: Data)
  27. }
  28. class AudioStreamManager {
  29. var microphoneUnit: AudioComponentInstance?
  30. weak var delegate: StreamDelegate?
  31. static var shared = AudioStreamManager()
  32. // Type used for audio unit elements. Bus 1 is input scope, element 1.
  33. private let bus1: AudioUnitElement = 1
  34. deinit {
  35. if let microphoneUnit = microphoneUnit {
  36. AudioComponentInstanceDispose(microphoneUnit)
  37. }
  38. }
  39. func configure() throws {
  40. try self.configureAudioSession()
  41. var audioComponentDescription = self.describeComponent()
  42. guard let remoteIOComponent = AudioComponentFindNext(nil, &audioComponentDescription) else {
  43. throw AudioStreamError.failedToFindAudioComponent
  44. }
  45. AudioComponentInstanceNew(remoteIOComponent, &self.microphoneUnit)
  46. try self.configureMicrophoneForInput()
  47. try self.setFormatForMicrophone()
  48. try self.setCallback()
  49. if let microphoneUnit = self.microphoneUnit {
  50. let status = AudioUnitInitialize(microphoneUnit)
  51. if status != noErr {
  52. throw AudioStreamError.failedToConfigure
  53. }
  54. }
  55. }
  56. func start() {
  57. guard let microphoneUnit = self.microphoneUnit else { return }
  58. AudioOutputUnitStart(microphoneUnit)
  59. }
  60. func stop() {
  61. guard let microphoneUnit = self.microphoneUnit else { return }
  62. AudioOutputUnitStop(microphoneUnit)
  63. }
  64. private func configureAudioSession() throws {
  65. let session = AVAudioSession.sharedInstance()
  66. try session.setCategory(.record)
  67. try session.setPreferredIOBufferDuration(10)
  68. }
  69. private func describeComponent() -> AudioComponentDescription {
  70. var description = AudioComponentDescription()
  71. description.componentType = kAudioUnitType_Output
  72. description.componentSubType = kAudioUnitSubType_RemoteIO
  73. description.componentManufacturer = kAudioUnitManufacturer_Apple
  74. description.componentFlags = 0
  75. description.componentFlagsMask = 0
  76. return description
  77. }
  78. private func configureMicrophoneForInput() throws {
  79. guard let microphoneUnit = self.microphoneUnit else {
  80. throw AudioStreamError.failedToFindMicrophoneUnit
  81. }
  82. var oneFlag: UInt32 = 1
  83. let status = AudioUnitSetProperty(microphoneUnit,
  84. kAudioOutputUnitProperty_EnableIO,
  85. kAudioUnitScope_Input,
  86. self.bus1,
  87. &oneFlag,
  88. UInt32(MemoryLayout<UInt32>.size))
  89. if status != noErr {
  90. throw AudioStreamError.failedToConfigure
  91. }
  92. }
  93. private func setFormatForMicrophone() throws {
  94. guard let microphoneUnit = self.microphoneUnit else {
  95. throw AudioStreamError.failedToFindMicrophoneUnit
  96. }
  97. /*
  98. Configure Audio format to match initial message sent
  99. over bidirectional stream. Config and below must match.
  100. */
  101. var asbd = AudioStreamBasicDescription()
  102. asbd.mSampleRate = Double(Constants.sampleRate)
  103. asbd.mFormatID = kAudioFormatLinearPCM
  104. asbd.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked
  105. asbd.mBytesPerPacket = 2
  106. asbd.mFramesPerPacket = 1
  107. asbd.mBytesPerFrame = 2
  108. asbd.mChannelsPerFrame = 1
  109. asbd.mBitsPerChannel = 16
  110. let status = AudioUnitSetProperty(microphoneUnit,
  111. kAudioUnitProperty_StreamFormat,
  112. kAudioUnitScope_Output,
  113. self.bus1,
  114. &asbd,
  115. UInt32(MemoryLayout<AudioStreamBasicDescription>.size))
  116. if status != noErr {
  117. throw AudioStreamError.failedToConfigure
  118. }
  119. }
  120. private func setCallback() throws {
  121. guard let microphoneUnit = self.microphoneUnit else {
  122. throw AudioStreamError.failedToFindMicrophoneUnit
  123. }
  124. var callbackStruct = AURenderCallbackStruct()
  125. callbackStruct.inputProc = recordingCallback
  126. callbackStruct.inputProcRefCon = nil
  127. let status = AudioUnitSetProperty(microphoneUnit,
  128. kAudioOutputUnitProperty_SetInputCallback,
  129. kAudioUnitScope_Global,
  130. self.bus1,
  131. &callbackStruct,
  132. UInt32(MemoryLayout<AURenderCallbackStruct>.size))
  133. if status != noErr {
  134. throw AudioStreamError.failedToConfigure
  135. }
  136. }
  137. }
  138. func recordingCallback(
  139. inRefCon: UnsafeMutableRawPointer,
  140. ioActionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>,
  141. inTimeStamp: UnsafePointer<AudioTimeStamp>,
  142. inBusNumber: UInt32,
  143. inNumberFrames: UInt32,
  144. ioData: UnsafeMutablePointer<AudioBufferList>?
  145. ) -> OSStatus {
  146. var status = noErr
  147. let channelCount: UInt32 = 1
  148. var bufferList = AudioBufferList()
  149. bufferList.mNumberBuffers = channelCount
  150. let buffers = UnsafeMutableBufferPointer<AudioBuffer>(start: &bufferList.mBuffers,
  151. count: Int(bufferList.mNumberBuffers))
  152. buffers[0].mNumberChannels = 1
  153. buffers[0].mDataByteSize = inNumberFrames * 2
  154. buffers[0].mData = nil
  155. // get the recorded samples
  156. guard let remoteIOUnit = AudioStreamManager.shared.microphoneUnit else { fatalError() }
  157. status = AudioUnitRender(remoteIOUnit,
  158. ioActionFlags,
  159. inTimeStamp,
  160. inBusNumber,
  161. inNumberFrames,
  162. UnsafeMutablePointer<AudioBufferList>(&bufferList))
  163. if (status != noErr) {
  164. return status
  165. }
  166. guard let bytes = buffers[0].mData else {
  167. fatalError("Unable to find pointer to the buffer audio data")
  168. }
  169. let data = Data(bytes: bytes, count: Int(buffers[0].mDataByteSize))
  170. DispatchQueue.main.async {
  171. AudioStreamManager.shared.delegate?.processAudio(data)
  172. }
  173. return noErr
  174. }