简体   繁体   中英

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

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.

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
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM