IOS/Objective-C/Swift: Handling UnsafePointer in Swift

86 views Asked by At

In an Objective-C method I use for speech recognition, I have some code to measure the speakers volume. When I try to translate it to Swift, however, I'm having trouble with how Swift handles pointers relative to Objective-C.

Here is the Objective-C doe:

    AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];

        [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {

            if ([buffer floatChannelData] != nil) {//open 1 in block

                float volume = fabsf(*buffer.floatChannelData[0]);

                    }
}];

Trying to do this in Swift does:

 let data = UnsafeMutablePointer<Float>(buffer.floatChannelData)


            if let data = &buffer.floatChannelData?[0] {
                let _ : Float = data[0]
          }

give multiple errors.

Thanks in advance for any suggestions.

1

There are 1 answers

0
OOPer On BEST ANSWER

I do not understand why you need data.

You can write something like this:

if buffer.floatChannelData != nil {
    let volume = buffer.floatChannelData![0].pointee
    //...
}

Or more swifty as follows:

if let floatChannelPointers = buffer.floatChannelData {
    let volume = floatChannelPointers[0].pointee
    //...
}