在 Swift 中连接两个音频文件并播放它们 [英] Concatenate two audio files in Swift and play them
问题描述
我尝试快速连接 .wav 音频文件.
I try to concatenate .wav audio files in swift.
这是我的代码:
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 上运行):
And get this error in the terminal (running on a iPhone) :
file:///var/mobile/Containers/Data/Application/3F49D360-B363-4600-B3BB-EE0810501910/Documents/resultmerge.wav
成功
failed 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.}
但我不知道为什么会出现此错误.如果您能给我任何帮助,我将不胜感激:)
But I don't know why I'm getting this error. I would greatly appreciate any help you can give me :)
推荐答案
我通过更改两件事让您的代码正常工作:
I got your code working by changing two things:
预设名称:从
AVAssetExportPresetPassthrough
到AVAssetExportPresetAppleM4A
输出文件类型:从AVFileTypeWAVE
到AVFileTypeAppleM4A
像这样修改你的 assetExport
声明:
Modify your assetExport
declaration like this:
var assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
assetExport.outputFileType = AVFileTypeAppleM4A
然后它将正确合并文件.
then it will properly merge the files.
看起来 AVAssetExportSession
只导出 M4A 格式而忽略其他预设.可能有一种方法可以让它导出其他格式(通过子类化它?),尽管我还没有探索这种可能性.
It looks like AVAssetExportSession
only exports M4A format and ignores other presets. There may be a way to make it export other formats (by subclassing it?), though I haven't explored this possibility yet.
这篇关于在 Swift 中连接两个音频文件并播放它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!