gpt4 book ai didi

ios - 我正在尝试合并音频和视频并保存到照片库 ios swift

转载 作者:行者123 更新时间:2023-11-28 08:03:23 24 4
gpt4 key购买 nike

我的音频和视频将来自 Document 目录。当我将视频保存到照片中时,一切正常。但是后来发生了这个错误并且没有保存。

failed Optional(Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x17044a2f0 {Error Domain=NSOSStatusErrorDomain Code=-12842 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12842), NSLocalizedDescription=The operation could not be completed})

这是我的功能

 func getData(){
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
print(directoryContents)

// if you want to filter the directory contents you can do like this:
videoUrlforMarge = directoryContents.filter{ $0.pathExtension == "mov" } as [AnyObject]
//videoUrlforMarge.append(directoryContents[1] as AnyObject)
print("this video \(videoUrlforMarge[0])")

audioUrl = directoryContents.filter{ $0.pathExtension == "caf" } as [AnyObject]

} catch let error as NSError {
print(error.localizedDescription)
}

}

这是我的合并函数

   func mergeFilesWithUrl(videoUrl:NSURL, audioUrl:NSURL)
{
let mixComposition : AVMutableComposition = AVMutableComposition()
var mutableCompositionVideoTrack : [AVMutableCompositionTrack] = []
var mutableCompositionAudioTrack : [AVMutableCompositionTrack] = []
let totalVideoCompositionInstruction : AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()


//start merge



let aVideoAsset : AVAsset = AVAsset(url: videoUrl as URL)
let aAudioAsset : AVAsset = AVAsset(url: audioUrl as URL)

mutableCompositionVideoTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid))
mutableCompositionAudioTrack.append( mixComposition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid))

guard aVideoAsset.tracks(withMediaType: AVMediaTypeVideo).count > 0 && aAudioAsset.tracks(withMediaType: AVMediaTypeAudio).count > 0 else{
return
}
let aVideoAssetTrack : AVAssetTrack = aVideoAsset.tracks(withMediaType: AVMediaTypeVideo)[0]
let aAudioAssetTrack : AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaTypeAudio)[0]



do{
try mutableCompositionVideoTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aVideoAssetTrack.timeRange.duration), of: aVideoAssetTrack, at: kCMTimeZero)

try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aVideoAssetTrack.timeRange.duration), of: aAudioAssetTrack, at: kCMTimeZero)

}catch{

}

totalVideoCompositionInstruction.timeRange = CMTimeRangeMake(kCMTimeZero,aVideoAssetTrack.timeRange.duration )

let mutableVideoComposition : AVMutableVideoComposition = AVMutableVideoComposition()
mutableVideoComposition.frameDuration = CMTimeMake(1, 30)

mutableVideoComposition.renderSize = CGSize(width: 1280, height: 720)


let VideoFilePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("mergeVideo\(arc4random()%1000)d")!.appendingPathExtension("mp4").absoluteString
if FileManager.default.fileExists(atPath: VideoFilePath)

{
do

{
try FileManager.default.removeItem(atPath: VideoFilePath)
}
catch { }

}
let tempfilemainurl = NSURL(string: VideoFilePath)!
let sourceAsset = AVURLAsset(url: tempfilemainurl as URL, options: nil)
let assetExport: AVAssetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetMediumQuality)!
assetExport.outputFileType = AVFileTypeQuickTimeMovie
assetExport.outputURL = tempfilemainurl as URL


assetExport.exportAsynchronously { () -> Void in
switch assetExport.status
{
case AVAssetExportSessionStatus.completed:
DispatchQueue.main.async(execute: {
do
{

self.userreponsevideoData = try NSData(contentsOf: tempfilemainurl as URL, options: NSData.ReadingOptions())
print("MB - \(self.userreponsevideoData.length) byte")
let assetsLib = ALAssetsLibrary()
assetsLib.writeVideoAtPath(toSavedPhotosAlbum: tempfilemainurl as URL!, completionBlock: nil)




}
catch
{

print(error)
}
})
case AVAssetExportSessionStatus.failed:
print("failed \(String(describing: assetExport.error))")
case AVAssetExportSessionStatus.cancelled:
print("cancelled \(String(describing: assetExport.error))")
default:
print("complete")

}

}
}

和其他我称之为合并功能的功能

func Action(){
guard videoUrlforMarge.count > 0 && audioUrl.count > 0 else{
return
}
let videoUrl = videoUrlforMarge[0]
let url = NSURL(fileURLWithPath: videoUrl.absoluteString!!)
let audio = audioUrl[0]
let urla = NSURL(fileURLWithPath: audio.absoluteString!!)

self.mergeFilesWithUrl(videoUrl: url as NSURL , audioUrl:
urla as NSURL

}

最佳答案

import Photos
import PhotosUI

我认为您在提供信息和代码方面做得很好。现在是星期天早上,专家们可能正在 sleep 吗?由于您的错误消息是如此隐晦,我认为这是一个权限问题,也许您还没有更新您的 Info.plist 以包含所需的“隐私 - 照片库使用说明”条目。此外,第一次运行时,用户必须接受您的访问请求才能保存到库。 [您没有显示该代码,并且您的代码都没有请求(和接收)来自照片库的数据——这就是为什么我认为这是问题所在。]需要这样的东西:

func configureGalleryAccess() {

PHPhotoLibrary.requestAuthorization({(_ status: PHAuthorizationStatus) -> Void in switch status {
case .authorized:
print("PHAuthorizationStatusAuthorized")
self.postAuthorizationLoadController() // replace with your code
case .denied:
print("PHAuthorizationStatusDenied")
case .notDetermined:
print("PHAuthorizationStatusNotDetermined")
case .restricted:
print("PHAuthorizationStatusRestricted")
}
})
}

错误消息提示您正在尝试保存它不允许的 nil 对象。因此,通过调试器运行程序,在保存对象/照片之前设置断点。如果你在你不期望的地方发现了 nil,就往回走,直到你找到问题所在。并在保存可选项时在保存前检查是否为 nil。

关于ios - 我正在尝试合并音频和视频并保存到照片库 ios swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45902217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com