我想知道如何为AVAssetExportSession时间戳制作时间范围,例如:
NSTimeInterval start = [[NSDate date] timeIntervalSince1970];
NSTimeInterval end = [[NSDate date] timeIntervalSince1970];
Run Code Online (Sandbox Code Playgroud)
我用于导出会话的代码如下:
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
exportSession.outputURL = videoURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
exportSession.timeRange = CMTimeRangeFromTimeToTime(start, end);
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
我正在尝试将.mov视频转换为.mp4,同时更正方向.我在下面使用的代码在录制视频时效果很好,UIImagePickerController但是如果从相机胶卷中选择了视频,我会收到此错误,我不明白为什么:
导出失败:操作已停止:错误域= AVFoundationErrorDomain代码= -11841"操作已停止"UserInfo = 0x1815ca50 {NSLocalizedDescription =操作已停止,NSLocalizedFailureReason =视频无法合成.}
我曾尝试将视频保存到另一个文件,但没有任何区别.
这是我用来转换视频的代码:
- (void)convertVideoToLowQuailtyAndFixRotationWithInputURL:(NSURL*)inputURL handler:(void (^)(NSURL *outURL))handler
{
if ([[inputURL pathExtension] isEqualToString:@"MOV"])
{
NSURL *outputURL = [inputURL URLByDeletingPathExtension];
outputURL = [outputURL URLByAppendingPathExtension:@"mp4"];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetTrack *sourceVideoTrack = [[avAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
AVAssetTrack *sourceAudioTrack = [[avAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
AVMutableComposition* composition = [AVMutableComposition composition];
AVMutableCompositionTrack *compositionVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo
preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, avAsset.duration)
ofTrack:sourceVideoTrack
atTime:kCMTimeZero error:nil];
[compositionVideoTrack setPreferredTransform:sourceVideoTrack.preferredTransform];
AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio
preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, avAsset.duration)
ofTrack:sourceAudioTrack …Run Code Online (Sandbox Code Playgroud) 导出后我AVMutableComposition使用PHPhotoLibrary将视频保存到相机胶卷.在creationRequestForAssetFromVideoAtFileURL:完成处理程序中,然后我在Instagram中打开已保存的视频,如下所示:
__block PHObjectPlaceholder *videoAssetPlaceholder;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:localVideoURL];
videoAssetPlaceholder = req.placeholderForCreatedAsset;
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
completion(YES);
NSString *localID = videoAssetPlaceholder.localIdentifier;
NSRange rangeOfSlash = [localID rangeOfString:@"/"];
if (rangeOfSlash.location != NSNotFound) {
NSString *assetID = [localID substringToIndex:rangeOfSlash.location];
NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@", assetID]];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
[[UIApplication sharedApplication] openURL:instagramURL];
}
}
}
}];
Run Code Online (Sandbox Code Playgroud)
Instagram打开的时间大约有50%,视频播放时间与预期相符.然而,另外50%的时间,视频和预览都是白色的,而我得到的只是声音.这通常通过选择另一个视频然后返回到我的视频来解决.视频在相机胶卷中完美播放,只有Instagram会导致问题.这是Instagram有问题还是我可能以错误的方式导出我的视频的问题?
这些是我的AVAssetExportSession设置:
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
presetName:AVAssetExportPresetHighestQuality]; …Run Code Online (Sandbox Code Playgroud) ios avmutablecomposition instagram avassetexportsession instagram-api
我开始说我花了很多时间在文档,帖子和其他地方搜索,但我无法找到解决这个问题的方法.
我AVAssetExportSession用于导出.mp4存储在AVAsset实例中的文件.我所做的是:
isExportable属性AVAssetexportPresets与AVAsset实例兼容的数组AVAssetExportPreset1920x1080,或者,如果不存在,我尝试导出媒体AVAssetExportPresetPassthrough(仅供参考,100%的时间,我需要的预设总是包含在列表中,但我也尝试了passthrough选项,但它无论如何都不起作用)的outputFileType是AVFileTypeMPEG4,我也试图通过分配.mp4扩展到该文件,但没有什么使得它的工作.我总是收到这个错误
错误域= AVFoundationErrorDomain代码= -11838"操作已停止"UserInfo = {NSUnderlyingError = 0x600000658c30 {错误域= NSOSStatusErrorDomain代码= -12109"(null)"},NSLocalizedFailureReason =此媒体不支持该操作.,NSLocalizedDescription =操作已停止}
下面是我正在使用的代码
func _getDataFor(_ item: AVPlayerItem, completion: @escaping (Data?) -> ()) {
guard item.asset.isExportable else {
completion(nil)
return
}
let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: item.asset)
var preset: String = AVAssetExportPresetPassthrough
if compatiblePresets.contains(AVAssetExportPreset1920x1080) { preset = AVAssetExportPreset1920x1080 }
guard
let exportSession = …Run Code Online (Sandbox Code Playgroud) 我在我的项目中使用AudioKit.通过使用混合节点操场示例中建议的过程,我正在播放多个音频.我的要求是将混合音频上传到服务器并显示和播放其他一些屏幕.我遵循了这个建议.如何在swift中将多个音频混合并保存到单个音频中,但它无法正常工作.
提供建议以获取混合音频输出以上载到服务器.
当我使用 avassetexportsession 时,有时会起作用,但有时会失败,并且出现以下错误。我查看了在线和苹果文档,但找不到有关此错误的任何内容。
错误:
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
not be completed" UserInfo={NSUnderlyingError=0x14dcf3bf0
{Error Domain=NSOSStatusErrorDomain Code=-12842 "(null)"},
NSLocalizedFailureReason=An unknown error occurred (-12842)
Run Code Online (Sandbox Code Playgroud)
代码:
let url = NSURL.fileURLWithPath(savedFileTest)
EditSongViewController.url.urlComplete = url
let exporter = AVAssetExportSession(asset: mixedFile, presetName: AVAssetExportPresetMediumQuality)
exporter!.audioMix = audioMixer
exporter!.outputURL = url
exporter!.outputFileType = AVFileTypeMPEG4
exporter!.exportAsynchronouslyWithCompletionHandler( {
// this handler gets called in a background thread!
switch exporter!.status {
case AVAssetExportSessionStatus.Failed:
self.indicator.stopAnimation(false, completion: nil)
//println("failed url=\(exporter.outputURL), error=\(exporter.error)")
return;
case AVAssetExportSessionStatus.Cancelled:
self.indicator.stopAnimation(false, completion: nil)
return;
default:
self.indicator.stopAnimation(false, completion: nil) …Run Code Online (Sandbox Code Playgroud) 我正在使用以下命令将 ID3 标签写入文件AVMetaDataItem
var soundFileMetadata = [AVMetadataItem]()
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeyArtist, "MyArtist")!)
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeySongName, "MySong")!)
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeyAlbum, "MyAlbum")!)
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeyUserGenre, "MyGenre")!)
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeyComposer, "MyComposer")!)
Run Code Online (Sandbox Code Playgroud)
这是createMetadata方便的方法:
func createMetadata(tagKey: String, _ tagValue: AnyObject?,
keySpace:String = AVMetadataKeySpaceiTunes) -> AVMutableMetadataItem? {
if let tagValue = tagValue {
let tag = AVMutableMetadataItem()
tag.keySpace = keySpace
tag.key = tagKey
tag.value = (tagValue as? String) ?? (tagValue as? Int)
return tag
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试也写年份标签,但没有成功:
let comps = NSDateComponents()
comps.year = 2010;
let yearTag = AVMutableMetadataItem()
yearTag.keySpace = AVMetadataKeySpaceID3
yearTag.key …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Apple TV 上使用以下代码保存视频:
func playerItemDidReachEnd(_ notification: Notification) {
if notification.object as? AVPlayerItem == player.currentItem {
player.seek(to: kCMTimeZero)
let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
let filename = "video.mp4"
let documentsDirectory = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last!
let outputURL = documentsDirectory.appendingPathComponent(filename)
exporter?.outputURL = NSURL.fileURL(withPath: outputURL.path)
exporter?.outputFileType = AVFileTypeMPEG4
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.appendingPathComponent(filename)?.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath!) {
} else {
exporter?.exportAsynchronously(completionHandler: {
print(exporter?.status.rawValue)
print(exporter?.error)
}) …Run Code Online (Sandbox Code Playgroud) 因此,我已经录制了两个 .mp4 并存储在应用程序中,我想将一个附加到另一个,然后导出为新视频。它有点有效,但不完全有效!
let composition = AVMutableComposition()
var track = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID:Int32(kCMPersistentTrackID_Invalid))
let videoAsset = AVAsset(url: AAA as URL) as AVAsset
let videoAsset2 = AVAsset(url: BBB as URL) as AVAsset
do {
try track?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: videoAsset.tracks(withMediaType: AVMediaType.video)[0] as AVAssetTrack, at: kCMTimeZero)
try track?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: videoAsset2.tracks(withMediaType: AVMediaType.video)[0] as AVAssetTrack, at: kCMTimeZero)
} catch {
print("darn")
}
let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)
exporter?.outputURL = CCC
exporter?.outputFileType = AVFileType.mp4
exporter?.shouldOptimizeForNetworkUse = true
exporter?.exportAsynchronously {
print("done?")
}
Run Code Online (Sandbox Code Playgroud)
这种方式组合了视频,但它在两个剪辑之间添加了大量黑屏,并删除了音频。我找不到这个问题的任何最新答案。感谢您的帮助!
我有一组存储为 AVURLAsset 的视频录制,我想将视频合并到 1 个剪辑中,以便它们连续播放,视频之间没有时间间隔。下面是我希望做的,但它只显示第一个视频。注意:我希望视频连续播放,并且每个视频之间没有空白。例如,如果当手机未录音时,录音 1 和录音 2 之间存在实时时间,则输出不应显示此情况。
感谢您的帮助!
func mergeVideos(handler: @escaping (_ asset: AVAssetExportSession)->()) {
let mixComposition = AVMutableComposition()
var videoTime = CMTime.zero
for video in self.recordings {
let tracks = video.tracks(withMediaType: .video)
let videoTrack = tracks[0]
let videoTimeRange = CMTimeRangeMake(start: .zero, duration: video.duration)
guard let compositionVideoTrack: AVMutableCompositionTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: Int32(kCMPersistentTrackID_Invalid)) else { return }
do {
try compositionVideoTrack.insertTimeRange(videoTimeRange, of: videoTrack, at: videoTime)
videoTime = CMTimeAdd(videoTime, video.duration)
} catch {
print("An error occurred")
return
}
} …Run Code Online (Sandbox Code Playgroud) xcode video-processing avassetwriter avassetexportsession swift