【发布时间】:2018-04-25 00:50:40
【问题描述】:
有没有办法将 Data 转换为 AVAsset/AVURLAsset 或更好的 AVPlayerItem? 我找到了一个将 Data 转换为 PHAsset 并需要先将其保存到桌面的答案。 有没有更好的办法?
【问题讨论】:
标签: ios swift nsdata avasset avplayeritem
有没有办法将 Data 转换为 AVAsset/AVURLAsset 或更好的 AVPlayerItem? 我找到了一个将 Data 转换为 PHAsset 并需要先将其保存到桌面的答案。 有没有更好的办法?
【问题讨论】:
标签: ios swift nsdata avasset avplayeritem
我设法做到了,有兴趣的人在这里。
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
}
}
【讨论】:
由于我还没有找到没有临时文件的方法,根据 Elsammak 的示例,这里有一个小助手类,负责删除临时文件(只要您使用,请保留 TemporaryMediaFile AVAsset,当对象被释放时临时文件将被删除,或者你可以手动调用.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()
【讨论】:
您可以执行以下操作: 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.");
}];
在完成任何你需要做的事情后不要忘记清理输出文件;)
【讨论】: