AudioController.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. import AVFoundation
  18. protocol AudioControllerDelegate {
  19. func processSampleData(_ data:Data) -> Void
  20. }
  21. class AudioController {
  22. var remoteIOUnit: AudioComponentInstance? // optional to allow it to be an inout argument
  23. var delegate : AudioControllerDelegate!
  24. static var sharedInstance = AudioController()
  25. deinit {
  26. AudioComponentInstanceDispose(remoteIOUnit!);
  27. }
  28. func prepare(specifiedSampleRate: Int) -> OSStatus {
  29. var status = noErr
  30. let session = AVAudioSession.sharedInstance()
  31. do {
  32. try session.setCategory(AVAudioSessionCategoryRecord)
  33. try session.setPreferredIOBufferDuration(10)
  34. } catch {
  35. return -1
  36. }
  37. var sampleRate = session.sampleRate
  38. print("hardware sample rate = \(sampleRate), using specified rate = \(specifiedSampleRate)")
  39. sampleRate = Double(specifiedSampleRate)
  40. // Describe the RemoteIO unit
  41. var audioComponentDescription = AudioComponentDescription()
  42. audioComponentDescription.componentType = kAudioUnitType_Output;
  43. audioComponentDescription.componentSubType = kAudioUnitSubType_RemoteIO;
  44. audioComponentDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
  45. audioComponentDescription.componentFlags = 0;
  46. audioComponentDescription.componentFlagsMask = 0;
  47. // Get the RemoteIO unit
  48. let remoteIOComponent = AudioComponentFindNext(nil, &audioComponentDescription)
  49. status = AudioComponentInstanceNew(remoteIOComponent!, &remoteIOUnit)
  50. if (status != noErr) {
  51. return status
  52. }
  53. let bus1 : AudioUnitElement = 1
  54. var oneFlag : UInt32 = 1
  55. // Configure the RemoteIO unit for input
  56. status = AudioUnitSetProperty(remoteIOUnit!,
  57. kAudioOutputUnitProperty_EnableIO,
  58. kAudioUnitScope_Input,
  59. bus1,
  60. &oneFlag,
  61. UInt32(MemoryLayout<UInt32>.size));
  62. if (status != noErr) {
  63. return status
  64. }
  65. // Set format for mic input (bus 1) on RemoteIO's output scope
  66. var asbd = AudioStreamBasicDescription()
  67. asbd.mSampleRate = sampleRate
  68. asbd.mFormatID = kAudioFormatLinearPCM
  69. asbd.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked
  70. asbd.mBytesPerPacket = 2
  71. asbd.mFramesPerPacket = 1
  72. asbd.mBytesPerFrame = 2
  73. asbd.mChannelsPerFrame = 1
  74. asbd.mBitsPerChannel = 16
  75. status = AudioUnitSetProperty(remoteIOUnit!,
  76. kAudioUnitProperty_StreamFormat,
  77. kAudioUnitScope_Output,
  78. bus1,
  79. &asbd,
  80. UInt32(MemoryLayout<AudioStreamBasicDescription>.size))
  81. if (status != noErr) {
  82. return status
  83. }
  84. // Set the recording callback
  85. var callbackStruct = AURenderCallbackStruct()
  86. callbackStruct.inputProc = recordingCallback
  87. callbackStruct.inputProcRefCon = nil
  88. status = AudioUnitSetProperty(remoteIOUnit!,
  89. kAudioOutputUnitProperty_SetInputCallback,
  90. kAudioUnitScope_Global,
  91. bus1,
  92. &callbackStruct,
  93. UInt32(MemoryLayout<AURenderCallbackStruct>.size));
  94. if (status != noErr) {
  95. return status
  96. }
  97. // Initialize the RemoteIO unit
  98. return AudioUnitInitialize(remoteIOUnit!)
  99. }
  100. func start() -> OSStatus {
  101. return AudioOutputUnitStart(remoteIOUnit!)
  102. }
  103. func stop() -> OSStatus {
  104. return AudioOutputUnitStop(remoteIOUnit!)
  105. }
  106. }
  107. func recordingCallback(
  108. inRefCon:UnsafeMutableRawPointer,
  109. ioActionFlags:UnsafeMutablePointer<AudioUnitRenderActionFlags>,
  110. inTimeStamp:UnsafePointer<AudioTimeStamp>,
  111. inBusNumber:UInt32,
  112. inNumberFrames:UInt32,
  113. ioData:UnsafeMutablePointer<AudioBufferList>?) -> OSStatus {
  114. var status = noErr
  115. let channelCount : UInt32 = 1
  116. var bufferList = AudioBufferList()
  117. bufferList.mNumberBuffers = channelCount
  118. let buffers = UnsafeMutableBufferPointer<AudioBuffer>(start: &bufferList.mBuffers,
  119. count: Int(bufferList.mNumberBuffers))
  120. buffers[0].mNumberChannels = 1
  121. buffers[0].mDataByteSize = inNumberFrames * 2
  122. buffers[0].mData = nil
  123. // get the recorded samples
  124. status = AudioUnitRender(AudioController.sharedInstance.remoteIOUnit!,
  125. ioActionFlags,
  126. inTimeStamp,
  127. inBusNumber,
  128. inNumberFrames,
  129. UnsafeMutablePointer<AudioBufferList>(&bufferList))
  130. if (status != noErr) {
  131. return status;
  132. }
  133. let data = Data(bytes: buffers[0].mData!, count: Int(buffers[0].mDataByteSize))
  134. DispatchQueue.main.async {
  135. AudioController.sharedInstance.delegate.processSampleData(data)
  136. }
  137. return noErr
  138. }