Skip to content

Commit b140c0a

Browse files
authored
Merge pull request #521 from Rexios80/feature/fix-microphone-in-use-crash
[audio_streamer] Catch errors when starting audio session on iOS
2 parents 3e646eb + b177b0a commit b140c0a

1 file changed

Lines changed: 24 additions & 12 deletions

File tree

packages/audio_streamer/ios/Classes/SwiftAudioStreamerPlugin.swift

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -119,20 +119,32 @@ public class SwiftAudioStreamerPlugin: NSObject, FlutterPlugin, FlutterStreamHan
119119
print("Unexpected error: \(error).")
120120
}
121121

122-
try! AVAudioSession.sharedInstance().setActive(true)
123122

124-
let input = engine.inputNode
125-
let bus = 0
123+
func startRecording() {
124+
engine = AVAudioEngine()
126125

127-
input.installTap(onBus: bus, bufferSize: 22050, format: input.inputFormat(forBus: bus)) {
128-
(buffer, time) -> Void in
129-
let samples = buffer.floatChannelData?[0]
130-
// audio callback, samples in samples[0]...samples[buffer.frameLength-1]
131-
let arr = Array(UnsafeBufferPointer(start: samples, count: Int(buffer.frameLength)))
132-
self.emitValues(values: arr)
133-
}
126+
do {
127+
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, options: .mixWithOthers)
128+
try AVAudioSession.sharedInstance().setActive(true)
129+
130+
if let sampleRateNotNull = sampleRate {
131+
// Try to set sample rate
132+
try AVAudioSession.sharedInstance().setPreferredSampleRate(Double(sampleRateNotNull))
133+
}
134134

135-
try! engine.start()
136-
}
135+
let input = engine.inputNode
136+
let bus = 0
137137

138+
input.installTap(onBus: bus, bufferSize: 22050, format: input.inputFormat(forBus: bus)) { buffer, _ -> Void in
139+
let samples = buffer.floatChannelData?[0]
140+
// audio callback, samples in samples[0]...samples[buffer.frameLength-1]
141+
let arr = Array(UnsafeBufferPointer(start: samples, count: Int(buffer.frameLength)))
142+
self.emitValues(values: arr)
143+
}
144+
145+
try engine.start()
146+
} catch {
147+
eventSink!(FlutterError(code: "100", message: "Unable to start audio session", details: error.localizedDescription))
148+
}
149+
}
138150
}

0 commit comments

Comments
 (0)