在将Swift 2转换为Swift 3

时间:2016-12-23 23:08:39

标签: swift generics swift3

我一直在努力抓住AUAudioUnits背后的想法,并在Apple的WWDC 2016 presentation video中给出了Xcode中的示例代码,并介绍了该主题。事实证明,这段代码是为Swift 2编写的,Swift 3引入了一种新的指针方式(如herehere所示)。现在我对使用Swift进行编程并且不熟悉它的一些概念是相当新的,我无法弄清楚如何手动执行从Swift 2到Swift 3的转换。甚至使用构建设置

  

使用Legacy Swift语言版本=是

我无法让它运行。

以下是Swift 2的代码,它正是视频中的代码:

import Foundation
import AVFoundation


class SquareWaveGenerator {
    let sampleRate: Double
    let frequency: Double
    let amplitude: Float

    var counter: Double = 0.0

    init(sampleRate: Double, frequency: Double, amplitude: Float) {
        self.sampleRate = sampleRate
        self.frequency = frequency
        self.amplitude = amplitude
    }

    func render(buffer: AudioBuffer) {
        let nframes = Int(buffer.mDataByteSize) / sizeof(Float)
        var ptr = UnsafeMutablePointer<Float>(buffer.mData)

        var j = self.counter
        let cycleLength = self.sampleRate / self.frequency
        let halfCycleLength = cycleLength / 2

        let amp = self.amplitude, minusAmp = -amp

        for _ in 0..<nframes {
            if j < halfCycleLength {
                ptr.pointee = amp
            } else {
                ptr.pointee = minusAmp
            }
            ptr = ptr.successor()
            j += 1.0
            if (j > cycleLength) {
                j -= cycleLength
            }
        }

        self.counter = j
    }
}

func main() {
    //Create an AudioComponentDescription for the input/output unit we want to use.
#if os(iOS)
    let kOutputUnitSubType = kAudioUnitSubType_RemoteIO
#else
    let kOutputUnitSubType = kAudioUnitSubType_HALOutput
#endif

    let ioUnitDesc = AudioComponentDescription(
        componentType: kAudioUnitType_Output,
        componentSubType: kOutputUnitSubType,
        componentManufacturer: kAudioUnitManufacturer_Apple,
        componentFlags: 0,
        componentFlagsMask: 0)

    let ioUnit = try! AUAudioUnit(componentDescription: ioUnitDesc, options: AudioComponentInstantiationOptions())

    /*
        Set things up to render at the same sample rate as the hardware,
        up to 2 channels. Note that the hardware format may not be a standard
        format, so we make a separate render format with the same sample rate
        and the desired channel count.
    */
    let hardwareFormat = ioUnit.outputBusses[0].format
    let renderFormat = AVAudioFormat(standardFormatWithSampleRate: hardwareFormat.sampleRate, channels: min(2,hardwareFormat.channelCount))

    try! ioUnit.inputBusses[0].setFormat(renderFormat)

    // Create square wave generators.
    let generatorLeft = SquareWaveGenerator(sampleRate: renderFormat.sampleRate, frequency: 440.0, amplitude: 0.1)
    let generatorRight = SquareWaveGenerator(sampleRate: renderFormat.sampleRate, frequency: 440.0, amplitude: 0.1)

    // Install a block which will be called to render.
    ioUnit.outputProvider = { (actionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>, timestamp: UnsafePointer<AudioTimeStamp>, frameCount: AUAudioFrameCount, busIndex: Int, rawBufferList: UnsafeMutablePointer<AudioBufferList>) -> AUAudioUnitStatus in

    let bufferList = UnsafeMutableAudioBufferListPointer(rawBufferList)
        if bufferList.count > 0 {
            generatorLeft.render(bufferList[0])
            if bufferList.count > 1 {
                generatorRight.render(bufferList[1])
            }
        }

        return noErr

    }

    // Allocate render resources, then start the audio hardware.
    try! ioUnit.allocateRenderResources()

    try! ioUnit.startHardware()

    sleep(3)
    ioUnit.stopHardware()
}

main()

此代码:

ptr.pointee = amp
[...]
ptr.pointee = minusAmp

引发以下错误:

  

'UnsafeMutablePointer'类型的值没有成员'pointee'

由于我无法手动解决此问题,我尝试手动将代码转换为Swift 3,希望问题能够得到解决。这是:

import Foundation
import AVFoundation


class SquareWaveGenerator {
    let sampleRate: Double
    let frequency: Double
    let amplitude: Float

    var counter: Double = 0.0

    init(sampleRate: Double, frequency: Double, amplitude: Float) {
        self.sampleRate = sampleRate
        self.frequency = frequency
        self.amplitude = amplitude
    }

    func render(buffer: AudioBuffer) {
        let nframes = Int(buffer.mDataByteSize) / MemoryLayout<Float>.size
        var ptr = buffer.mData

        var j = self.counter
        let cycleLength = self.sampleRate / self.frequency
        let halfCycleLength = cycleLength / 2

        let amp = self.amplitude, minusAmp = -amp

        for _ in 0..<nframes {
            if j < halfCycleLength {
                ptr?.pointee = amp
            } else {
                ptr?.pointee = minusAmp
            }
            ptr = ptr?.advanced(by: 1)
            j += 1.0
            if (j > cycleLength) {
                j -= cycleLength
            }
        }

        self.counter = j
    }
}

func main() {
    //Create an AudioComponentDescription for the input/output unit we want to use.
#if os(iOS)
    let kOutputUnitSubType = kAudioUnitSubType_RemoteIO
#else
    let kOutputUnitSubType = kAudioUnitSubType_HALOutput
#endif

    let ioUnitDesc = AudioComponentDescription(
        componentType: kAudioUnitType_Output,
        componentSubType: kOutputUnitSubType,
        componentManufacturer: kAudioUnitManufacturer_Apple,
        componentFlags: 0,
        componentFlagsMask: 0)

    let ioUnit = try! AUAudioUnit(componentDescription: ioUnitDesc, options: AudioComponentInstantiationOptions())

    /*
        Set things up to render at the same sample rate as the hardware,
        up to 2 channels. Note that the hardware format may not be a standard
        format, so we make a separate render format with the same sample rate
        and the desired channel count.
    */
    let hardwareFormat = ioUnit.outputBusses[0].format
    let renderFormat = AVAudioFormat(standardFormatWithSampleRate: hardwareFormat.sampleRate, channels: min(2,hardwareFormat.channelCount))

    try! ioUnit.inputBusses[0].setFormat(renderFormat)

    // Create square wave generators.
    let generatorLeft = SquareWaveGenerator(sampleRate: renderFormat.sampleRate, frequency: 440.0, amplitude: 0.1)
    let generatorRight = SquareWaveGenerator(sampleRate: renderFormat.sampleRate, frequency: 440.0, amplitude: 0.1)

    // Install a block which will be called to render.
    ioUnit.outputProvider = { (actionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>, timestamp: UnsafePointer<AudioTimeStamp>, frameCount: AUAudioFrameCount, busIndex: Int, rawBufferList: UnsafeMutablePointer<AudioBufferList>) -> AUAudioUnitStatus in

    let bufferList = UnsafeMutableAudioBufferListPointer(rawBufferList)
        if bufferList.count > 0 {
            generatorLeft.render(buffer: bufferList[0])
            if bufferList.count > 1 {
                generatorRight.render(buffer: bufferList[1])
            }
        }

        return noErr

    }

    // Allocate render resources, then start the audio hardware.
    try! ioUnit.allocateRenderResources()

    try! ioUnit.startHardware()

    sleep(3)
    ioUnit.stopHardware()
}

main()

我再次遇到上述错误

  

'UnsafeMutablePointer'类型的值没有成员'pointee'

最后,我认为像

这样的东西
ptr?.storeBytes(of: T, as: T.Type)

应该能够取代“pointee”构造。如果我理解正确,“T”是我想要存储在指针位置的值。在我的情况下,那将是“放大器”。 “amp”的类型为Float。

但无论我做了什么,我都无法运行代码。它只是不接受像

这样的东西
ptr?.storeBytes(of: amp, as: Float())

投掷

  

无法将'Float'类型的值转换为预期的参数类型'T.Type'

ptr?.storeBytes(of: amp, as: Float.self)

不再立即抛出错误并正确编译,但在运行时,收到lldb错误消息

  

致命错误:storeBytes未对齐原始指针

从本质上讲,我不知道我在做什么,在这种情况下不理解'T.Type'的概念,而且我被困住了。所以我有两个问题:

  

1)如何解决此问题并使代码运行?

     

2)我在哪里可以了解更多关于这些类型的建筑的类型,这将有助于我了解它们是什么以及它们的意思?

1 个答案:

答案 0 :(得分:4)

您在此处遇到的问题是,虽然AudioBuffer.mData曾经是UnsafeMutablePointer,但它现在是UnsafeMutableRawPointer,这是Swift 3中的新功能。要按照以前的方式处理该数据,可以将引用的内存绑定到Float类型,如下所示:

guard let mData = buffer.mData 
    else { return /* or error */ }
let nframes = Int(buffer.mDataByteSize) / MemoryLayout<Float>.size
var ptr = mData.bindMemory(to: Float.self, capacity: nframes)

现在ptrUnsafeMutablePointer<Float>,这是您之前使用过的,您应该能够毫无困难地访问其pointee媒体资源。

注意:每当您在函数声明中看到T.Type时,它就会询问类型本身,而不是类型的实例。在这种情况下,您希望传递Float的类型,即Float.self。另一方面,调用Float()会创建一个新的Float实例。

最后,我不是继续直接使用ptr,而是创建一个缓冲区,它至少会让你在调试模式和更好的界面中检查边界:

let buffer = UnsafeMutableBufferPointer<Float>(start: ptr, count: frames)
// ...
for i in 0..<nframes {
    if j < halfCycleLength {
        buffer[i] = amp
    } else {
        buffer[i] = minusAmp
    }
    j += 1.0
    // ...
}