gpt4 book ai didi

swift - 在 Swift 中连接两个音频文件并播放它们

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:13 25 4
gpt4 key购买 nike

我尝试快速连接 .wav 音频文件。

这是我的代码:

func merge(audio1: NSURL, audio2:  NSURL) {


var error:NSError?

var ok1 = false
var ok2 = false


var documentsDirectory:String = paths[0] as! String

//Create AVMutableComposition Object.This object will hold our multiple AVMutableCompositionTrack.
var composition = AVMutableComposition()
var compositionAudioTrack1:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
var compositionAudioTrack2:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())

//create new file to receive data
var documentDirectoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as! NSURL
var fileDestinationUrl = documentDirectoryURL.URLByAppendingPathComponent("resultmerge.wav")
println(fileDestinationUrl)


var url1 = audio1
var url2 = audio2


var avAsset1 = AVURLAsset(URL: url1, options: nil)
var avAsset2 = AVURLAsset(URL: url2, options: nil)

var tracks1 = avAsset1.tracksWithMediaType(AVMediaTypeAudio)
var tracks2 = avAsset2.tracksWithMediaType(AVMediaTypeAudio)

var assetTrack1:AVAssetTrack = tracks1[0] as! AVAssetTrack
var assetTrack2:AVAssetTrack = tracks2[0] as! AVAssetTrack


var duration1: CMTime = assetTrack1.timeRange.duration
var duration2: CMTime = assetTrack2.timeRange.duration

var timeRange1 = CMTimeRangeMake(kCMTimeZero, duration1)
var timeRange2 = CMTimeRangeMake(duration1, duration2)


ok1 = compositionAudioTrack1.insertTimeRange(timeRange1, ofTrack: assetTrack1, atTime: kCMTimeZero, error: nil)
if ok1 {

ok2 = compositionAudioTrack2.insertTimeRange(timeRange2, ofTrack: assetTrack2, atTime: duration1, error: nil)

if ok2 {
println("success")
}
}

//AVAssetExportPresetPassthrough => concatenation
var assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough)
assetExport.outputFileType = AVFileTypeWAVE
assetExport.outputURL = fileDestinationUrl
assetExport.exportAsynchronouslyWithCompletionHandler({
switch assetExport.status{
case AVAssetExportSessionStatus.Failed:
println("failed \(assetExport.error)")
case AVAssetExportSessionStatus.Cancelled:
println("cancelled \(assetExport.error)")
default:
println("complete")
var audioPlayer = AVAudioPlayer()
audioPlayer = AVAudioPlayer(contentsOfURL: fileDestinationUrl, error: nil)
audioPlayer.prepareToPlay()
audioPlayer.play()
}

})

}

并在终端中出现此错误(在 iPhone 上运行):

file:///var/mobile/Containers/Data/Application/3F49D360-B363-4600-B3BB-EE0810501910/Documents/resultmerge.wav

成功

失败 Error Domain=AVFoundationErrorDomain Code=-11838 "Opération interrompue"UserInfo=0x174269ac0 {NSLocalizedDescription=Opération interrompue, NSLocalizedFailureReason=L'opération n'est pas prize en charge pour ce contenu multimedia.}

但我不知道为什么会出现此错误。如果您能给我任何帮助,我将不胜感激 :)

最佳答案

对于 swift 3.0 -归功于 @Peyman(经过轻微修改)

var mergeAudioURL = NSURL()

func mergeAudioFiles(audioFileUrls: NSArray) {
let composition = AVMutableComposition()

for i in 0 ..< audioFileUrls.count {

let compositionAudioTrack :AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())

let asset = AVURLAsset(url: (audioFileUrls[i] as! NSURL) as URL)

let track = asset.tracks(withMediaType: AVMediaTypeAudio)[0]

let timeRange = CMTimeRange(start: CMTimeMake(0, 600), duration: track.timeRange.duration)

try! compositionAudioTrack.insertTimeRange(timeRange, of: track, at: composition.duration)
}

let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
self.mergeAudioURL = documentDirectoryURL.appendingPathComponent("FinalAudio.m4a")! as URL as NSURL

let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
assetExport?.outputFileType = AVFileTypeAppleM4A
assetExport?.outputURL = mergeAudioURL as URL
assetExport?.exportAsynchronously(completionHandler:
{
switch assetExport!.status
{
case AVAssetExportSessionStatus.failed:
print("failed \(assetExport?.error)")
case AVAssetExportSessionStatus.cancelled:
print("cancelled \(assetExport?.error)")
case AVAssetExportSessionStatus.unknown:
print("unknown\(assetExport?.error)")
case AVAssetExportSessionStatus.waiting:
print("waiting\(assetExport?.error)")
case AVAssetExportSessionStatus.exporting:
print("exporting\(assetExport?.error)")
default:
print("Audio Concatenation Complete")
}
})
}

关于swift - 在 Swift 中连接两个音频文件并播放它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30479403/

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