如何将数据转换为AVAsset?

7

有没有一种方法可以将Data转换为AVAsset/AVURLAsset,或者更好的AVPlayerItem? 我找到了一个答案,它将Data转换为PHAsset,并要求首先将其保存到桌面。 有更好的方法吗?

3个回答

5

因为我没有找到不使用临时文件的方法,所以基于Elsammak的例子,这里有一个小帮助类来处理删除临时文件(只要在使用AVAsset期间保留TemporaryMediaFile,当对象被解除分配或者你可以手动调用.deleteFile()删除临时文件):

import Foundation
import AVKit

class TemporaryMediaFile {
    var url: URL?

    init(withData: Data) {
        let directory = FileManager.default.temporaryDirectory
        let fileName = "\(NSUUID().uuidString).mov"
        let url = directory.appendingPathComponent(fileName)
        do {
            try withData.write(to: url)
            self.url = url
        } catch {
            print("Error creating temporary file: \(error)")
        }
    }

    public var avAsset: AVAsset? {
        if let url = self.url {
            return AVAsset(url: url)
        }

        return nil
    }

    public func deleteFile() {
        if let url = self.url {
            do {
                try FileManager.default.removeItem(at: url)
                self.url = nil
            } catch {
                print("Error deleting temporary file: \(error)")
            }
        }
    }

    deinit {
        self.deleteFile()
    }
}

使用示例:

    let data = Data(bytes: ..., count: ...)

    let tempFile = TemporaryMediaFile(withData: data)
    if let asset = tempFile.avAsset {
        self.player = AVPlayer(playerItem: AVPlayerItem(asset: asset))
    }

    // ..keep "tempFile" around while it's playing..

    tempFile.deleteFile()

3
我已经完成了它,这是给任何有兴趣的人。
extension Data {
    func getAVAsset() -> AVAsset {
        let directory = NSTemporaryDirectory()
        let fileName = "\(NSUUID().uuidString).mov"
        let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])
        try! self.write(to: fullURL!)
        let asset = AVAsset(url: fullURL!)
        return asset
    }
}

2
作者询问是否可以在不创建临时文件的情况下从数据初始化AVAsset。 - vahotm

-3
您可以执行以下操作: 1. 使用AVAssetExportSession将您的AVAsset对象导出到文件路径URL。 2. 使用其dataWithContentsOfURL方法将其转换为NSData。
NSURL *fileURL = nil;
__block NSData *assetData = nil;
// asset is you AVAsset object
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];

exportSession.outputURL = fileURL;
// e.g .mov type 
exportSession.outputFileType = AVFileTypeQuickTimeMovie; 

[exportSession exportAsynchronouslyWithCompletionHandler:^{
    assetData = [NSData dataWithContentsOfURL:fileURL];
    NSLog(@"AVAsset saved to NSData.");
}];

不要忘记在处理完输出文件后清理它;)

作者询问是否可以从Data初始化AVAsset,而不是反过来。 - vahotm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接