如何在swift中创建VTCompressionSession?

时间:2014-06-10 05:45:38

标签: objective-c macos cocoa swift xcode6

我一直在寻找如何创建 VTCompressionSession swift )在2014 WWDC Video - 'Direct Access to Video Encoding and Decoding'中提到。

以下代码适用于Objective-C:

#import <Foundation/Foundation.h>
#import <VideoToolbox/VideoToolbox.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        VTCompressionSessionRef session;
        VTCompressionSessionCreate(NULL, 500, 500, kCMVideoCodecType_H264, NULL, NULL, NULL, NULL, NULL, &session);

        NSLog(@"created VTCompressionSession");
    }
    return 0;
}

但无论我尝试过什么,我找不到将VTCompressionSessionCreate导入 swift 的方法。

import Foundation
import VideoToolbox

VideoToolbox.VTCompressionSessionCreate()

println("created VTCompressionSession")

此代码例如以Module 'VideoToolbox' has no member named 'VTCompressionSessionCreate'打破 只需调用VTCompressionSessionCreate即可创建错误消息Use of unresolved identifier 'VTCompressionSessionCreate'

看起来API没有在 swift 中公开,因为我可以调用像VTCompressionSessionEncodeFrame这样的方法。我错过了一些明显的东西吗?

3 个答案:

答案 0 :(得分:3)

我的解决方法是编写一个objective-c函数并通过bridging-header将其暴露给swift:

Compression.h

#import <VideoToolbox/VideoToolbox.h>
VTCompressionSessionRef CreateCompressionSession();

Compression.m

#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#import <VideoToolbox/VideoToolbox.h>

VTCompressionSessionRef CreateCompressionSession(){
    NSLog(@"CreateCompressionSession");
    VTCompressionSessionRef session;
    VTCompressionSessionCreate(NULL, 500, 500, kCMVideoCodecType_H264, NULL, NULL, NULL, NULL, NULL, &session);
    return session;
}

流桥接-Header.h

#import "CompressionSession.h"

现在,您可以在 swift

中运行以下代码
import Cocoa
import Foundation
import VideoToolbox

let session = CreateCompressionSession()

答案 1 :(得分:0)

以下是我在swift中的表现:

var session: Unmanaged<VTCompressionSession>?
VTCompressionSessionCreate(nil, 320, 200, CMVideoCodecType(kCMVideoCodecType_H264), nil, nil, nil, nil, nil, &session)
compressionSession = session?.takeRetainedValue()

,其中

var compressionSession: VTCompressionSessionRef?

不要忘记import CoreMedia

答案 2 :(得分:0)

对于Swift 3:

var compressionSesionOut = UnsafeMutablePointer<VTCompressionSession?>.allocate(capacity: 1)
VTCompressionSessionCreate(nil, 100, 100, kCMVideoCodecType_H264, nil, nil, nil, nil, nil, compressionSesionOut)

然后,您可以像这样访问它,例如:

let vtCompressionSession: VTCompressionSession = compressionSesionOut.pointee.unsafelyUnwrapped
VTSessionSetProperty(vtCompressionSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue)