Objective c 如何在swift中创建VTCompressionSession?

Objective c 如何在swift中创建VTCompressionSession?,objective-c,macos,cocoa,swift,xcode6,Objective C,Macos,Cocoa,Swift,Xcode6,我一直在到处寻找如何创建一个VTCompressionSession(在swift)的方法,如中所述 以下代码适用于Objective-C: #import <Foundation/Foundation.h> #import <VideoToolbox/VideoToolbox.h> int main(int argc, const char * argv[]) { @autoreleasepool { VTCompressionSessionR

我一直在到处寻找如何创建一个VTCompressionSession(在swift)的方法,如中所述

以下代码适用于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;
}
例如,此代码中断为:
模块“VideoToolbox”没有名为“VTCompressionSessionCreate”的成员。

只需调用
vtcompressioncreate
就会创建错误消息
使用未解析标识符“vtcompressioncreate”


看起来API没有在swift中公开,因为我可以调用类似
vtcompressionencodeframe
的方法。我是否遗漏了一些明显的内容?

我的解决方法是编写一个objective-c函数,并通过桥接头将其公开给swift:

压缩

#import <VideoToolbox/VideoToolbox.h>
VTCompressionSessionRef CreateCompressionSession();
现在,您可以在swift中运行以下代码:

import Cocoa
import Foundation
import VideoToolbox

let session = CreateCompressionSession()

以下是我在swift中的做法:

var session: Unmanaged<VTCompressionSession>?
VTCompressionSessionCreate(nil, 320, 200, CMVideoCodecType(kCMVideoCodecType_H264), nil, nil, nil, nil, nil, &session)
compressionSession = session?.takeRetainedValue()
不要忘记导入适用于Swift 3的CoreMedia:

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

这个例子在OSX10.10或IOS8上不再适用(如果它曾经起作用的话)。为
VTCompressionSessionCreate
outputCallback参数(第8个参数)传入nil将给出错误代码-12092。上述参数将给出类型错误。在xcode 7/swift 2中,以下操作可能有效:var会话:Unsafemeutablepointer=nil let status=VTCompressionSessionCreate(kCFAllocatorDefault,Int32(像素宽度),Int32(像素高度),KCMVideocodeType_H264,nil,nil,nil/*使用默认值*/,nil,nil,session)
import Cocoa
import Foundation
import VideoToolbox

let session = CreateCompressionSession()
var session: Unmanaged<VTCompressionSession>?
VTCompressionSessionCreate(nil, 320, 200, CMVideoCodecType(kCMVideoCodecType_H264), nil, nil, nil, nil, nil, &session)
compressionSession = session?.takeRetainedValue()
var compressionSession: VTCompressionSessionRef?
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)