Search code examples
swiftcore-audiounsafemutablepointer

kAudioUnitProperty_MatrixLevels in Swift


To query a MatrixMixer AudioUnit you do the following:

// code from MatrixMixerTest sample project in c++

UInt32 dims[2];
UInt32 theSize =  sizeof(UInt32) * 2;
Float32 *theVols = NULL;
OSStatus result;


ca_require_noerr (result = AudioUnitGetProperty (au, kAudioUnitProperty_MatrixDimensions,   
                        kAudioUnitScope_Global, 0, dims, &theSize), home);

theSize = ((dims[0] + 1) * (dims[1] + 1)) * sizeof(Float32);

theVols = static_cast<Float32*> (malloc (theSize));

ca_require_noerr (result = AudioUnitGetProperty (au, kAudioUnitProperty_MatrixLevels,   
                        kAudioUnitScope_Global, 0, theVols, &theSize), home);

The return value on AudioUnitGetProperty for the kAudioUnitProperty_MatrixLevels is (defined in the documentation and in the sample code) a Float32.

I am trying to find the matrix levels in swift and can get the matrix dimensions without an issue. But I am not sure how to create an empty array of Float32 elements that is a UnsafeMutablePointer<Void>. Here's what I have tried without success:

var size = ((dims[0] + 1) * (dims[1] + 1)) * UInt32(sizeof(Float32))
var vols = UnsafeMutablePointer<Float32>.alloc(Int(size))

In the MatrixMixerTest the array is used like: theVols[0]


Solution

  • May need to be modified depending on how you converted other parts, but the last part of your C++ code can be written in Swift like this:

        theSize = ((dims[0] + 1) * (dims[1] + 1)) * UInt32(sizeof(Float32))
    
        var theVols: [Float32] = Array(count: Int(theSize)/sizeof(Float32), repeatedValue: 0)
    
        result = AudioUnitGetProperty(au, kAudioUnitProperty_MatrixLevels,
                kAudioUnitScope_Global, 0, &theVols, &theSize)
        guard result == noErr else {
            //...
            fatalError()
        }
    

    When a C-function based API is claiming a UnsafeMutablePointer<Void>, you just need an Array variable of an arbitrary type, and pass it as inout parameter.