Am at the beginning of a voice recording app. I store incoming voice data into a buffer array, and write 50 of them to a file. The code works fine, Sample One.
However, I would like the recorded files to be smaller. So here I try to add an AVAudioMixer to downsize the sampling. But this code sample gives me two errors. Sample Two
The first error I get is when I call audioEngine.attach(downMixer). The debugger gives me nine of these errors:
throwing -10878
The second error is a crash when I try to write to audioFile. Of course they might all be related, so am looking to include the mixer successfully first.
But I do need help as I am just trying to piece these all together from tutorials, and when it comes to audio, I know less than anything else.
Sample One
//these two lines are in the init of the class that contains this function...
node = audioEngine.inputNode
recordingFormat = node.inputFormat(forBus: 0)
func startRecording()
{
audioBuffs = []
x = -1
node.installTap(onBus: 0, bufferSize: 8192, format: recordingFormat, block: {
[self]
(buffer, _) in
x += 1
audioBuffs.append(buffer)
if x >= 50 {
audioFile = makeFile(format: recordingFormat, index: fileCount)
mainView?.setLabelText(tag: 3, text: "fileIndex = \(fileCount)")
fileCount += 1
for i in 0...49 {
do {
try audioFile!.write(from: audioBuffs[i]);
} catch {
mainView?.setLabelText(tag: 4, text: "write error")
stopRecording()
}
}
...cleanup buffer code
}
})
audioEngine.prepare()
do {
try audioEngine.start()
} catch let error { print ("oh catch \(error)") }
}
Sample Two
//these two lines are in the init of the class that contains this function
node = audioEngine.inputNode
recordingFormat = node.inputFormat(forBus: 0)
func startRecording() {
audioBuffs = []
x = -1
// new code
let format16KHzMono = AVAudioFormat.init(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: 11025.0, channels: 1, interleaved: true)
let downMixer = AVAudioMixerNode()
audioEngine.attach(downMixer)
// installTap on the mixer rather than the node
downMixer.installTap(onBus: 0, bufferSize: 8192, format: format16KHzMono, block: {
[self]
(buffer, _) in
x += 1
audioBuffs.append(buffer)
if x >= 50 {
// use a different format in creating the audioFile
audioFile = makeFile(format: format16KHzMono!, index: fileCount)
mainView?.setLabelText(tag: 3, text: "fileIndex = \(fileCount)")
fileCount += 1
for i in 0...49 {
do {
try audioFile!.write(from: audioBuffs[i]);
} catch {
stopRecording()
}
}
...cleanup buffers...
}
})
let format = node.inputFormat(forBus: 0)
// new code
audioEngine.connect(node, to: downMixer, format: format)//use default input format
audioEngine.connect(downMixer, to: audioEngine.outputNode, format: format16KHzMono)//use new audio format
downMixer.outputVolume = 0.0
audioEngine.prepare()
do {
try audioEngine.start()
} catch let error { print ("oh catch \(error)") }
}