iOS 将 2 个或更多音频文件合并(混合)为 wav 格式

标签 ios swift audio avassetexportsession avmutablecomposition

我在下面创建了合并方法(加入、联合,我不确定哪个词是正确的,我想从 2 个或更多个中制作 1 个音频,而不是一个接一个地播放,而是一次播放每个) .作为输入,我有多个 .wav 格式的音频文件,我想输出 1 个 .wav 格式。

  func merge(audioUrls: [NSURL], resultName : String = "result") {

    let resultNameWithExtension = resultName + ".wav"

    //Create AVMutableComposition Object.This object will hold our multiple AVMutableCompositionTrack.
    let composition = AVMutableComposition()


    //create new file to receive data
    //let documentDirectoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
    let outputFilePath = NSTemporaryDirectory().stringByAppendingPathComponent(resultNameWithExtension)
    let fileDestinationUrl = NSURL(fileURLWithPath: outputFilePath)
    print(fileDestinationUrl)

    StorageManager.sharedInstance.deleteFileAtPath(NSTemporaryDirectory().stringByAppendingPathComponent(resultNameWithExtension))

    var avAssets: [AVURLAsset] = []
    var assetTracks: [AVAssetTrack] = []
    var timeRanges: [CMTimeRange] = []

    for audioUrl in audioUrls {
      let compositionAudioTrack:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID:kCMPersistentTrackID_Invalid)

      let avAsset = AVURLAsset(URL: audioUrl, options: nil)
      avAssets.append(avAsset)

      let assetTrack = avAsset.tracksWithMediaType(AVMediaTypeAudio)[0]
      assetTracks.append(assetTrack)

      let duration = assetTrack.timeRange.duration
      let timeRange = CMTimeRangeMake(kCMTimeZero, duration)
      timeRanges.append(timeRange)

      do {
        try compositionAudioTrack.insertTimeRange(timeRange, ofTrack: assetTrack, atTime: kCMTimeZero)
      } catch let error as NSError {
        print("compositionAudioTrack insert error: \(error)")
      }
    }

    let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough)!
    assetExport.outputFileType = AVFileTypeWAVE
    assetExport.outputURL = fileDestinationUrl
    assetExport.exportAsynchronouslyWithCompletionHandler({
      self.delegate?.assetExportSessionDidFinishExport(assetExport, outputFilePath: outputFilePath)
    })
  }

我的问题是它不起作用,我不知道为什么。我得到的错误:

Error Domain=AVFoundationErrorDomain Code=-11838 "Operation Stopped" UserInfo={NSLocalizedDescription=Operation Stopped, NSLocalizedFailureReason=The operation is not supported for this media.})

当我将预设和输出类型更改为 .m4a 时,它可以正常工作,但我需要 .wav。当我有相同格式的输入时,它应该与 .wav 一起工作,对吧?感谢您的帮助

最佳答案

如果你想将一个音频文件混合或重叠到另一个音频文件,那么你应该编写这段代码,但你只能生成 .m4a 文件而不是 .wav 文件。我使用 .mp3 文件作为输入文件。

在 swift3 中:

例如:

func playmerge(audio1: NSURL, audio2:  NSURL)
{
    let composition = AVMutableComposition()
    let compositionAudioTrack1:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
    let compositionAudioTrack2:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())

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

    let filemanager = FileManager.default
    if (!filemanager.fileExists(atPath: self.fileDestinationUrl.path))
    {
        do
        {
            try filemanager.removeItem(at: self.fileDestinationUrl)
        }
        catch let error as NSError
        {
            NSLog("Error: \(error)")
        }

        if (theError == nil)
        {
            print("The music files has been Removed.")
        }
        else
        {
            print("Error")
        }
    }
    else
    {
        do
        {
            try filemanager.removeItem(at: self.fileDestinationUrl)
        }
        catch let error as NSError
        {
            NSLog("Error: \(error)")
        }

        if (theError == nil)
        {
            print("The music files has been Removed.")
        }
        else
        {
            print("Error")
        }
    }

    let url1 = audio1
    let url2 = audio2

    let avAsset1 = AVURLAsset(url: url1 as URL, options: nil)
    let avAsset2 = AVURLAsset(url: url2 as URL, options: nil)

    var tracks1 = avAsset1.tracks(withMediaType: AVMediaTypeAudio)
    var tracks2 = avAsset2.tracks(withMediaType: AVMediaTypeAudio)

    let assetTrack1:AVAssetTrack = tracks1[0]
    let assetTrack2:AVAssetTrack = tracks2[0]

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

    let timeRange1 = CMTimeRangeMake(kCMTimeZero, duration1)
    let timeRange2 = CMTimeRangeMake(kCMTimeZero, duration2)
    do
    {
        try compositionAudioTrack1.insertTimeRange(timeRange1, of: assetTrack1, at: kCMTimeZero)
        try compositionAudioTrack2.insertTimeRange(timeRange2, of: assetTrack2, at: kCMTimeZero)
    }
    catch
    {
        print(error)
    }

    let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
    assetExport?.outputFileType = AVFileTypeAppleM4A
    assetExport?.outputURL = fileDestinationUrl
    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("complete")
        }

        do
        {
            self.player = try AVAudioPlayer(contentsOf: self.fileDestinationUrl)
            self.player?.numberOfLoops = 0
            self.player?.prepareToPlay()
            self.player?.volume = 1.0
            self.player?.play()
            self.player?.delegate=self
        }
        catch let error as NSError
        {
            print(error)
        }
    })
}

关于iOS 将 2 个或更多音频文件合并(混合)为 wav 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37680414/

相关文章:

c++ - 使用 Superpowered Audio Kit 在音轨之间正确转换

ios - 如何从 App Delegate 重新加载 UIViewController 数据

ios - Swift:点击手势无法识别

ios - 使用 AVAudioPlayer 播放音频

swift - 解决文本字段和按钮图像问题带来的问题

ios - Swift Parse Query 如何在对象中的对象之后创建 uialertview ?

ios - 使用扩展音频文件写入和读取音频文件

ios - 如何将 iOS 上的 "may not respond to XXX"警告转换为错误?

ios - UITableViewCell 内的 TableView - 必须注册一个 nib 或类

ios - UIScrollView ContentSize 高度太大