|
| 1 | +import AVFoundation |
| 2 | +import Foundation |
| 3 | + |
| 4 | +public enum MicrophoneError: Error { |
| 5 | + case conversionFailed(details: String) |
| 6 | +} |
| 7 | +public class Microphone { |
| 8 | + public static let sampleRate: Double = 44100 |
| 9 | + public static let isLinear16PCM: Bool = true |
| 10 | + // Linear16 PCM is a standard format well-supported by EVI (although you must send |
| 11 | + // a `session_settings` message to inform EVI of the sample rate). Because there is |
| 12 | + // a wide variance of the native format/ sample rate from input devices, we use the |
| 13 | + // AVAudioConverter API to convert the audio to this standard format in order to |
| 14 | + // remove all guesswork. |
| 15 | + private static let desiredInputFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: sampleRate, channels: 1, interleaved: false)! |
| 16 | + |
| 17 | + public var audioEngine: AVAudioEngine |
| 18 | + private var inputNode: AVAudioInputNode |
| 19 | + private var isMuted: Bool = false |
| 20 | + private var onError: ((MicrophoneError) -> Void)? |
| 21 | + |
| 22 | + public init() { |
| 23 | + self.isMuted = false |
| 24 | + self.audioEngine = AVAudioEngine() |
| 25 | + self.inputNode = audioEngine.inputNode |
| 26 | + |
| 27 | + do { |
| 28 | + let outputNode: AVAudioOutputNode = audioEngine.outputNode |
| 29 | + let mainMixerNode: AVAudioMixerNode = audioEngine.mainMixerNode |
| 30 | + audioEngine.connect(mainMixerNode, to: outputNode, format: nil) |
| 31 | + |
| 32 | + // Voice processing is a feature that can help reduce echo and background noise |
| 33 | + // It is very important for audio chat applications like EVI, because without |
| 34 | + // echo cancellation, EVI will hear its own output and attempt to respond to it. |
| 35 | + |
| 36 | + // `setVoiceProcessingEnabled` should be enabled on *both* the input and output nodes |
| 37 | + // because it works by observing signals that are sent to the output node (the |
| 38 | + // speaker) and then "cancels" the echoes of those signals from what comes |
| 39 | + // back into the input node (the microphone). |
| 40 | + try self.inputNode.setVoiceProcessingEnabled(true) |
| 41 | + try outputNode.setVoiceProcessingEnabled(true) |
| 42 | + |
| 43 | + if #available(iOS 17.0, *) { |
| 44 | + let duckingConfig = AVAudioVoiceProcessingOtherAudioDuckingConfiguration(enableAdvancedDucking: false, duckingLevel: .max) |
| 45 | + inputNode.voiceProcessingOtherAudioDuckingConfiguration = duckingConfig |
| 46 | + } |
| 47 | + } catch { |
| 48 | + print("Error setting voice processing: \(error)") |
| 49 | + return |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public func onError(_ onError: @escaping (MicrophoneError) -> Void) { |
| 54 | + self.onError = onError |
| 55 | + } |
| 56 | + |
| 57 | + public func mute() { |
| 58 | + self.isMuted = true |
| 59 | + } |
| 60 | + |
| 61 | + public func unmute() { |
| 62 | + self.isMuted = false |
| 63 | + } |
| 64 | + |
| 65 | + public func startRecording(onBase64EncodedAudio: @escaping (String) -> Void) throws { |
| 66 | + let nativeInputFormat = self.inputNode.inputFormat(forBus: 0) |
| 67 | + // The sample rate is "samples per second", so multiplying by 0.1 should get us chunks of about 100ms |
| 68 | + let inputBufferSize = UInt32(nativeInputFormat.sampleRate * 0.1) |
| 69 | + self.inputNode.installTap(onBus: 0, bufferSize: inputBufferSize, format: nativeInputFormat) { (buffer, time) in |
| 70 | + let convertedBuffer = AVAudioPCMBuffer(pcmFormat: Microphone.desiredInputFormat, frameCapacity: 1024)! |
| 71 | + |
| 72 | + var error: NSError? = nil |
| 73 | + |
| 74 | + if self.isMuted { |
| 75 | + // The standard behavior for muting is to send audio frames filled with empty data |
| 76 | + // (versus not sending anything during mute). This helps audio systems distinguish |
| 77 | + // between muted-but-still-active streams and streams that have become disconnected. |
| 78 | + let silence = Data(repeating: 0, count: Int(convertedBuffer.frameCapacity) * Int(convertedBuffer.format.streamDescription.pointee.mBytesPerFrame)) |
| 79 | + onBase64EncodedAudio(silence.base64EncodedString()) |
| 80 | + return |
| 81 | + } |
| 82 | + let inputAudioConverter = AVAudioConverter(from: nativeInputFormat, to: Microphone.desiredInputFormat)! |
| 83 | + let status = inputAudioConverter.convert(to: convertedBuffer, error: &error, withInputFrom: {inNumPackets, outStatus in |
| 84 | + outStatus.pointee = .haveData |
| 85 | + buffer.frameLength = inNumPackets |
| 86 | + return buffer |
| 87 | + }) |
| 88 | + |
| 89 | + if status == .haveData { |
| 90 | + let byteLength = Int(convertedBuffer.frameLength) * Int(convertedBuffer.format.streamDescription.pointee.mBytesPerFrame) |
| 91 | + let audioData = Data(bytes: convertedBuffer.audioBufferList.pointee.mBuffers.mData!, count: byteLength) |
| 92 | + let base64String = audioData.base64EncodedString() |
| 93 | + onBase64EncodedAudio(base64String) |
| 94 | + return |
| 95 | + } |
| 96 | + if error != nil { |
| 97 | + self.onError?(MicrophoneError.conversionFailed(details: error!.localizedDescription)) |
| 98 | + return |
| 99 | + } |
| 100 | + self.onError?(MicrophoneError.conversionFailed(details: "Unexpected status during audio conversion: \(status)")) |
| 101 | + } |
| 102 | + |
| 103 | + if (!audioEngine.isRunning) { |
| 104 | + try audioEngine.start() |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + public func stopRecording() { |
| 109 | + audioEngine.stop() |
| 110 | + self.inputNode.removeTap(onBus: 0) |
| 111 | + } |
| 112 | +} |
0 commit comments