合成视频和音频 - 视频的音频消失了

2023-12-05

我的问题是,我正在使用下面的功能来编写视频和音频。我想保留视频的原始声音,但它不知何故消失了,我没有任何线索。

我从这里得到这个功能这个答案

我尝试在附加后立即更改卷AVMutableCompositionTrack但没用

例如;

mutableVideoCompositionTrack.prefferedVolume = 1.0
mutableAudioCompositionTrack.prefferedVolume = 0.05

但您仍然只能听到音频文件。

功能;

private func mergeAudioAndVideo(audioUrl: URL, videoUrl: URL, completion: @escaping (Bool)->Void){

    let mixComposition = AVMutableComposition()
    var mutableCompositionVideoTrack : [AVMutableCompositionTrack] = []
    var mutableCompositionAudioTrack : [AVMutableCompositionTrack] = []
    let totalVideoCompositionInstruction = AVMutableVideoCompositionInstruction()

    let videoAsset = AVAsset(url: videoUrl)
    let audioAsset = AVAsset(url: audioUrl)

    mutableCompositionVideoTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid))
    mutableCompositionAudioTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid))
    mutableCompositionAudioTrack[0].preferredVolume = 0.05
    mutableCompositionVideoTrack[0].preferredVolume = 1.0        


    let videoAssetTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo)[0]
    let audioAssetTrack = audioAsset.tracks(withMediaType: AVMediaTypeAudio)[0]

    do {
        try mutableCompositionVideoTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAssetTrack.timeRange.duration), of: videoAssetTrack, at: kCMTimeZero)
        try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAssetTrack.timeRange.duration), of: audioAssetTrack, at: kCMTimeZero)
    }catch{
        print("ERROR#1")
    }

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

    let mutableVideoComposition = AVMutableVideoComposition()
    mutableVideoComposition.frameDuration = CMTimeMake(1, 30)
    mutableVideoComposition.renderSize = CGSize(width: 1280, height: 720)

    //exporting

    savePathUrl = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("merged").appendingPathExtension("mov")

    let assetExport = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)!
    assetExport.outputFileType = AVFileTypeMPEG4
    assetExport.outputURL = savePathUrl
    assetExport.shouldOptimizeForNetworkUse = true

    do {
        try FileManager.default.removeItem(at: savePathUrl)
    }catch {
        print(error)
    }

    assetExport.exportAsynchronously { 
        switch assetExport.status{
        case .completed:
            print("completed")
            completion(true)
        default:
            print("failed \(assetExport.error!)")
            completion(false)
        }
    }

}

您可以分别调整视频和音频的音量@Faruk,这里有一些代码。

        //Extract audio from the video and the music
let audioMix: AVMutableAudioMix = AVMutableAudioMix()
var audioMixParam: [AVMutableAudioMixInputParameters] = []

let assetVideoTrack: AVAssetTrack = assetVideo.tracksWithMediaType(AVMediaTypeAudio)[0]
let assetMusicTrack: AVAssetTrack = assetMusic.tracksWithMediaType(AVMediaTypeAudio)[0]

let videoParam: AVMutableAudioMixInputParameters = AVMutableAudioMixInputParameters(track: assetVideoTrack)
videoParam.trackID = compositionAudioVideo.trackID

let musicParam: AVMutableAudioMixInputParameters = AVMutableAudioMixInputParameters(track: assetMusicTrack)
musicParam.trackID = compositionAudioMusic.trackID

//Set final volume of the audio record and the music
videoParam.setVolume(volumeVideo, atTime: kCMTimeZero)
musicParam.setVolume(volumeAudio, atTime: kCMTimeZero)

//Add setting
audioMixParam.append(musicParam)
audioMixParam.append(videoParam)

//Add audio on final record
//First: the audio of the record and Second: the music
do {
try compositionAudioVideo.insertTimeRange(CMTimeRangeMake(kCMTimeZero, assetVideo.duration), ofTrack: assetVideoTrack, atTime: kCMTimeZero)
} catch _ {
assertionFailure()
}

do {
try compositionAudioMusic.insertTimeRange(CMTimeRangeMake(CMTimeMake(Int64(startAudioTime * 10000), 10000), assetVideo.duration), ofTrack: assetMusicTrack, atTime: kCMTimeZero)
} catch _ {
assertionFailure()
}

//Add parameter
audioMix.inputParameters = audioMixParam

let completeMovie = "\(docsDir)/\(randomString(5)).mp4"
let completeMovieUrl = NSURL(fileURLWithPath: completeMovie)
let exporter: AVAssetExportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)!

exporter.outputURL = completeMovieUrl
exporter.outputFileType = AVFileTypeMPEG4
exporter.audioMix = audioMix
exporter.exportAsynchronouslyWithCompletionHandler({ 

switch exporter.status {

case AVAssetExportSessionStatus.Completed:
    print("success with output url \(completeMovieUrl)")
    case  AVAssetExportSessionStatus.Failed:
        print("failed \(String(exporter.error))")
    case AVAssetExportSessionStatus.Cancelled:
        print("cancelled \(String(exporter.error))")
    default:
        print("complete")
    }            
})

}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

合成视频和音频 - 视频的音频消失了 的相关文章

  • iOS:从相机获取逐像素数据

    我知道 AVFoundation 及其捕获支持 虽然不太熟悉 但是 我没有看到任何易于访问的 API 来获取逐像素数据 每像素 RGB 或类似数据 我确实记得在文档中读过这是可能的 但我真的不明白如何做到 所以 这可以做到吗 如果是这样 怎
  • 迭代弱引用数组,其中对象符合 Swift 中的协议

    我想将对象存储在数组中 其中对象很弱 并且符合协议 但是当我尝试循环它时 我收到编译器错误 public class Weak
  • 如何计算iOS 11不同方向的尺寸?

    我根据具有水平滚动和自定义布局的 UICollectionView 的安全区域来计算 itemSize 但对于 iPhone X 来说 安全区域对于不同的方向有不同的大小 我的问题是如何计算 viewWillTransition 函数中横向
  • 如何快速将 void 块传递给 objc_setAssociatedObject

    我正在尝试通过扩展向 UIView 添加点击手势支持 使用 Objective C 非常简单 但是当我尝试在运行时属性上设置 void 返回块时 出现以下错误 错误 类型 gt Void 不符合协议 AnyObject 这是计算的属性 va
  • 更改accessoryType Swift 的颜色

    我想将我的手机配件类型的颜色从蓝色更改为白色 textColor 已设置为白色 你们有人知道该怎么做吗 My Code cell accessoryType UITableViewCellAccessoryType Checkmark 您可
  • Swift 中获取 UIPanGestureRecognizer 的起点和终点

    我在用着UIPanGestureRecognizer在一个项目上 我想取起点和终点 我试着做touchesBegin 但没有得到满足我需要的代码 如何获取起点和终点UIPanGestureRecognizer 对于您的情况 您可能希望将我的
  • Apple Watch 表 - 前 4 行未出现

    我在添加行时遇到问题WKInterfaceTable在苹果手表上 奇怪的是 无论我做什么 前 4 行都显示为空 我尝试手动添加行并循环 没关系 我相信我的代码很好 因为第五行和其他行看起来都很好 发生的情况如下 进一步滚动 My code
  • 无需 nib 以编程方式实例化 UIViewController

    我想创建一个UIViewController以编程方式进行 无需使用笔尖或故事板 我认为实施该计划就足够了UIViewController as class TestViewController UIViewController overr
  • UIImage 在编码/解码时不等效

    我一直在对我的模型进行一些测试 以确保当我将它们编码为 JSON 然后使用它们解码回来时它们是相等的JSONEncoder Decoder 然而 我的一项测试失败了 罪魁祸首是UIImage 我已确保在编码 解码过程中没有抛出任何错误 首先
  • DropDelegate Safari 拖动图像

    我正在尝试实施DropDelegate模式以允许将图像拖到我的视图中并加载它们 这对于取景器中的图像效果很好 但是当将图像从 safari 拖到我的视图中时 这不起作用 我注意到typeIdentifier or UTType所提供的信息
  • 在不使用PrepareForSegue的情况下在segue之间传递数据

    我正在使用情节提要创建一个用户设置帐户 分 5 个步骤 每个步骤都有一个 ViewController 1 输入姓名 联系人等 2 导入照片 3 输入等 4 更多输入 5 确认页面 如果用户单击 确认 gt 获取所有输入并上传到解析 当我在
  • 如何快速将云Firestore中的数据保存到变量中?

    我想将文档中的特定字段保存到变量中 到目前为止我的代码 func getDocument path String field String nil gt some Any var returnVar Any DEFAULT VAL var
  • Firebase数据库在批准后保存数据

    我在 iOS 应用程序上使用 firebase 数据库 我正在快速写作 我正在使用 发送 按钮在我的 firebaseDatabase 上写入数据 例如文本字段和标签值 有什么方法可以接受或拒绝我的数据库中的数据吗 我的意思是 如果用户向文
  • 如何从Vuforia GL矩阵计算相机位置?

    我计算了 a 的相机位置SCNScene这是在 Vuforia 中渲染的 然而 物体并没有固定在标记上 而是在移动时跳跃 场景中的立方体仅以正交方式出现 无论设备如何围绕侧面移动都无法看到 相机位置是根据每一帧计算的 Get model v
  • Swift - 向每个页面添加相同的导航栏项目

    我正在尝试将相同的导航栏项目添加到应用程序中的每个选项卡 我目前已在我的 homeController 中正确设置了它们 但我想将代码移动到一个单独的文件中 并在我想要的任何地方远程实现它 例如 在导航栏左侧添加一个 搜索 图标 而不必在每
  • 无法在 mac 屏幕保护程序发布版本上加载图像(它适用于 Xcode 调试版本)

    我从这里得到了这个 mac 屏幕保护程序示例here https github com elpsk PaskySaver 我将其更改为显示图像而不是文本字段 问题是这样的 它可以显示任何 Xcode 对象 例如 textView textF
  • 如何在 SKAction 中途反转精灵所遵循的路径方向?

    我有一个 SKSpriteNode 它使用 SKAction 沿着圆形路径移动 create the path our sprite will travel along let circlePath CGPathCreateWithElli
  • 连接到 Apple Music

    所以我尝试使用 React Native 应用程序从 iOS 设备连接到 Apple Music 有一个 API 可以执行相同的操作 但我需要从 storekit 框架调用一个函数 提出个性化请求 苹果音乐API https develop
  • 将 Facebook 图片 URL 上传到 Firebase 存储

    我正在尝试将用户的 Facebook 个人资料图片上传到 Firebase 存储 let dictionary result as NSDictionary let data dictionary objectForKey data let
  • 使用 NSOutlineView 作为文件系统目录浏览器的 Swift 代码

    我已经在这段 Swift 代码上苦苦挣扎了一段时间 但没有发现问题 代码 下面应该提供文件目录作为 NSOutlineView 的数据源 GUI 非常简单 只是一个带有 NSOutlineView 和 OutlineViewControll

随机推荐