Using Chris Adamson's book Learning Core Audio I'm getting familiar with Core Audio for Mac/iOS. The code examples are 100% Objective-C. I'm trying to follow along using Swift 3.
This small piece of software is used to find usable AudioStreamBasicDescription
s for a given file type and format.
import Foundation
import AudioToolbox
// Create ID for specific fileType and fileFormat
var fileTypeAndFormat = AudioFileTypeAndFormatID()
fileTypeAndFormat.mFileType = kAudioFileCAFType
fileTypeAndFormat.mFormatID = kAudioFormatLinearPCM
// Target: Gather possible AudioStreamBasicDescriptions for given fileType and fileFormat
// Get size of array containing all available AudioStreamBasicDescriptions
var possibleError = noErr
var infoSize: UInt32 = 0
possibleError = AudioFileGetGlobalInfoSize(kAudioFileGlobalInfo_AvailableStreamDescriptionsForFormat,
UInt32(MemoryLayout<AudioFileTypeAndFormatID>.stride),
&fileTypeAndFormat,
&infoSize)
assert(possibleError == noErr)
// Get number of AudioStreamBasicDescription stored in array
let asbdCount = Int(infoSize) / MemoryLayout<AudioStreamBasicDescription>.stride
// Allocate memory for array to store AudioStreamBasicDescriptions in
var asbds = [AudioStreamBasicDescription](repeating: AudioStreamBasicDescription(), count: asbdCount)
// Fill array with all available AudioStreamBasicDescriptions
possibleError = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_AvailableStreamDescriptionsForFormat,
UInt32(MemoryLayout<AudioFileTypeAndFormatID>.stride),
&fileTypeAndFormat,
&infoSize,
&asbds)
assert(possibleError == noErr)
// Print each AudioStreamBasicDescription of array
for n in 0..<asbdCount {
var reformattedID = asbds[n].mFormatID.bigEndian
// TODO: This seems too ugly to be true
withUnsafePointer(to: &reformattedID) { stringIDPtr in
print(String(format: "%d: mFormatID: %s, mFormatFlags: %d, mBitsPerChannel: %d", n, stringIDPtr,
asbds[n].mFormatFlags, asbds[n].mBitsPerChannel))
}
}
In an production environment the assert
s should be replaced with better error handling, but correct error handling was not the purpose of this script.
Specific parts I'd like to get a review on:
- The memory allocation to store available
StreamDescriptions
for format in. Is the allocation via array Swift-style-conform? - Getting the
mFormatID
of anAudioStreamBasicDescription
viawithUnsafePointer(to: &reformattedID)
seems utterly unpleasant. Can this be realized in a more elegant way?