Swift回调函数

时间:2015-11-21 14:49:24

标签: swift macos the-amazing-audio-engine

我尝试使用The Amazing Audio Engine在OS X上使用Swift录制一些音频。为此,我需要实现一个回调函数,它将接收音频并对其执行某些操作。有关如何使用Objective-C执行此操作的文档有一些examples

@interface MyAudioReceiver : NSObject <AEAudioReceiver>
@end
@implementation MyAudioReceiver
static void receiverCallback(__unsafe_unretained MyAudioReceiver *THIS,
 __unsafe_unretained AEAudioController *audioController,
 void *source,
 const AudioTimeStamp *time,
 UInt32 frames,
 AudioBufferList *audio) {

 // Do something with 'audio'
}
-(AEAudioReceiverCallback)receiverCallback {
 return receiverCallback;
}
@end
...
id<AEAudioReceiver> receiver = [[MyAudioReceiver alloc] init];

id<AEAudioReceiver> receiver = [AEBlockAudioReceiver audioReceiverWithBlock:
 ^(void *source,
 const AudioTimeStamp *time,
 UInt32 frames,
 AudioBufferList *audio) {
 // Do something with 'audio'
}];

据我所知:

var audioController: AEAudioController? = nil
audioController = AEAudioController(audioDescription: AEAudioStreamBasicDescriptionInterleaved16BitStereo, inputEnabled: true)
do {
    try audioController?.start()
} catch {
    NSLog("An error happened while starting AEAudioController.")
}

let receiver = MyAudioReceiver();
audioController?.addInputReceiver(receiver)

class MyAudioReceiver : NSObject, AEAudioReceiver {
    var receiverCallback: AEAudioReceiverCallback! {
        // what do I do here?
    }
}

现在我在receiverCallback属性中收到错误。我在这里走在正确的轨道上还是我的方法完全错了?

我无法弄清楚如何在Swift中完成同样的事情。我该怎么做?

2 个答案:

答案 0 :(得分:0)

在Swift中,函数和块几乎被平等对待,具有closures的统一概念。我建议你阅读(以及其他文档)以理解闭包语法和语义。

答案 1 :(得分:0)

这是我工作的taae swift项目的一个例子

var receiverCallback: AEAudioReceiverCallback! {
    return  { (receiver:AnyObject?, audioController:AEAudioController?, source:UnsafeMutablePointer<Void>, time:UnsafePointer<AudioTimeStamp>, frames:UInt32, audio:UnsafeMutablePointer<AudioBufferList>) -> Void in
        //do some thing with audio data here
    }
}