복붙노트

[SWIFT] AudioMixInputParameters AVFoundation를 사용하여 각 비디오 트랙에 여러 볼륨을 설정하면 스위프트 아이폰 OS에서 작동하지 않습니다

SWIFT

AudioMixInputParameters AVFoundation를 사용하여 각 비디오 트랙에 여러 볼륨을 설정하면 스위프트 아이폰 OS에서 작동하지 않습니다

해결법


  1. 1.여기에 내 질문에 대한 작업 솔루션입니다 :

    여기에 내 질문에 대한 작업 솔루션입니다 :

    func addVolumeToIndividualVideoClip(_ assetURL: URL, video: VideoFileModel, completion : ((_ session: AVAssetExportSession?, _ outputURL : URL?) -> ())?){
    
            //Create Asset from Url
            let filteredVideoAsset: AVAsset = AVAsset(url: assetURL)
    
            video.fileID = String(video.videoID)
    
            //Get the path of App Document Directory
            let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    
            let url = URL(fileURLWithPath: documentDirectory).appendingPathComponent("\(video.fileID)_\("FilterVideo").mov")
    
            let filePath = url.path
            let fileManager = FileManager.default
    
            do {
                if fileManager.fileExists(atPath: filePath) {
                    print("FILE AVAILABLE")
                    try fileManager.removeItem(atPath:filePath)
                } else {
                    print("FILE NOT AVAILABLE")
                }
            } catch _ {
            }
    
    
            let composition: AVMutableComposition = AVMutableComposition()
            let compositionVideo: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())
            let compositionAudioVideo: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
    
    
            //Add video to the final record
            do {
                 try compositionVideo.insertTimeRange(CMTimeRangeMake(kCMTimeZero, filteredVideoAsset.duration), of: filteredVideoAsset.tracks(withMediaType: AVMediaTypeVideo)[0], at: kCMTimeZero)
            } catch _ {
            }
    
            //Extract audio from the video and the music
            let audioMix: AVMutableAudioMix = AVMutableAudioMix()
            var audioMixParam: [AVMutableAudioMixInputParameters] = []
    
            let assetVideoTrack: AVAssetTrack = filteredVideoAsset.tracks(withMediaType: AVMediaTypeAudio)[0]
    
            let videoParam: AVMutableAudioMixInputParameters = AVMutableAudioMixInputParameters(track: assetVideoTrack)
            videoParam.trackID = compositionAudioVideo.trackID
    
            //Set final volume of the audio record and the music
            videoParam.setVolume(video.videoVolume, at: kCMTimeZero)
    
            //Add setting
            audioMixParam.append(videoParam)
    
            //Add audio on final record
            //First: the audio of the record and Second: the music
            do {
                try compositionAudioVideo.insertTimeRange(CMTimeRangeMake(kCMTimeZero, filteredVideoAsset.duration), of: assetVideoTrack, at: kCMTimeZero)
            } catch _ {
                assertionFailure()
            }
    
            //Fading volume out for background music
            let durationInSeconds = CMTimeGetSeconds(filteredVideoAsset.duration)
    
            let firstSecond = CMTimeRangeMake(CMTimeMakeWithSeconds(0, 1), CMTimeMakeWithSeconds(1, 1))
            let lastSecond = CMTimeRangeMake(CMTimeMakeWithSeconds(durationInSeconds-1, 1), CMTimeMakeWithSeconds(1, 1))
    
            videoParam.setVolumeRamp(fromStartVolume: 0, toEndVolume: video.videoVolume, timeRange: firstSecond)
            videoParam.setVolumeRamp(fromStartVolume: video.videoVolume, toEndVolume: 0, timeRange: lastSecond)
    
            //Add parameter
            audioMix.inputParameters = audioMixParam
    
            //Remove the previous temp video if exist
            let filemgr = FileManager.default
            do {
                if filemgr.fileExists(atPath: "\(video.fileID)_\("FilterVideo").mov") {
                    try filemgr.removeItem(atPath: "\(video.fileID)_\("FilterVideo").mov")
                } else {
                }
            } catch _ {
            }
    
            //Exporte the final record’
            let exporter: AVAssetExportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)!
            exporter.outputURL = url
            exporter.outputFileType = AVFileTypeMPEG4
            exporter.audioMix = audioMix
    
            exporter.exportAsynchronously(completionHandler: { () -> Void in
                completion!(exporter, url)
    
               // self.saveVideoToLibrary(from: filePath)
            })
        }
    

  2. 2.나는 AVAssetExportPresetPassthrough의 사전 설정과 자산을 수출하는 출력 볼륨에 영향이없는 것을 발견했다. 내가 AVAssetExportPresetLowQuality을 사용하려고 할 때, 볼륨 변경은 성공적으로 적용.

    나는 AVAssetExportPresetPassthrough의 사전 설정과 자산을 수출하는 출력 볼륨에 영향이없는 것을 발견했다. 내가 AVAssetExportPresetLowQuality을 사용하려고 할 때, 볼륨 변경은 성공적으로 적용.

    나는 그것이 더 나은 문서화 어딘가에 할 :(

    작업 코드 :

    // Assume we have:
    let composition: AVMutableComposition
    var inputParameters = [AVAudioMixInputParameters]()
    
    // We add a track
    let trackComposition = composition.addMutableTrack(...)
    
    // Configure volume for this track
    let inputParameter = AVMutableAudioMixInputParameters(track: trackComposition)
    inputParameter.setVolume(desiredVolume, at: startTime)
    
    // It works even without setting the `trackID`
    // inputParameter.trackID = trackComposition.trackID
    
    inputParameters.append(inputParameter)
    
    // Apply gathered `inputParameters` before exporting
    let audioMix = AVMutableAudioMix()
    audioMix.inputParameters = inputParameters
    
    // I found it's not working, if using `AVAssetExportPresetPassthrough`,
    // so try `AVAssetExportPresetLowQuality` first
    let export = AVAssetExportSession(..., presetName: AVAssetExportPresetLowQuality)
    export.audioMix = audioMix
    

    각각의 삽입을위한 다른 볼륨 설정 compositionTrack 같은 여러 assetTrack 삽입, 이것을 테스트 하였다. 작동하는 것 같다.

  3. from https://stackoverflow.com/questions/54804888/setting-multiple-volumes-to-each-video-tracks-using-audiomixinputparameters-avfo by cc-by-sa and MIT license