在swift中追加或连接音频文件

时间:2015-03-31 20:59:40

标签: ios swift audio-recording

嗨我想附加语音文件。

我用AVAudioRecorder录制语音,但要播放我需要拨打的录音"停止",但播放后我想继续录音。与原生iOS语音备忘录应用程序一样。

我应该使用AVMutableCompositionTrack吗?如何在swift中执行此操作?谢谢!

1 个答案:

答案 0 :(得分:3)

如果您希望暂停录制并稍后继续播放,可以使用AVAudioRecorder的pause()函数而不是stop(),并且当您再次使用play()时它将继续录制。

但是,如果您希望实际连接音频文件,可以这样做:

func concatenateFiles(audioFiles: [NSURL], completion: (concatenatedFile: NSURL?) -> ()) {
    guard audioFiles.count > 0 else {
        completion(concatenatedFile: nil)
        return
    }

    if audioFiles.count == 1 {
        completion(concatenatedFile: audioFiles.first)
        return
    }

    // Concatenate audio files into one file
    var nextClipStartTime = kCMTimeZero
    let composition = AVMutableComposition()
    let track = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)

    // Add each track
    for recording in audioFiles {
        let asset = AVURLAsset(URL: NSURL(fileURLWithPath: recording.path!), options: nil)
        if let assetTrack = asset.tracksWithMediaType(AVMediaTypeAudio).first {
            let timeRange = CMTimeRange(start: kCMTimeZero, duration: asset.duration)
            do {
                try track.insertTimeRange(timeRange, ofTrack: assetTrack, atTime: nextClipStartTime)
                nextClipStartTime = CMTimeAdd(nextClipStartTime, timeRange.duration)
            } catch {
                print("Error concatenating file - \(error)")
                completion(concatenatedFile: nil)
                return
            }
        }
    }

    // Export the new file
    if let exportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough) {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documents = NSURL(string: paths.first!)

        if let fileURL = documents?.URLByAppendingPathComponent("file_name.caf") {
            // Remove existing file
            do {
                try NSFileManager.defaultManager().removeItemAtPath(fileURL.path!)
                print("Removed \(fileURL)")
            } catch {
                print("Could not remove file - \(error)")
            }

            // Configure export session output
            exportSession.outputURL = NSURL.fileURLWithPath(fileURL.path!)
            exportSession.outputFileType = AVFileTypeCoreAudioFormat

            // Perform the export
            exportSession.exportAsynchronouslyWithCompletionHandler() { handler -> Void in
                if exportSession.status == .Completed {
                    print("Export complete")
                    dispatch_async(dispatch_get_main_queue(), {
                        completion(file: fileURL)
                    })
                    return
                } else if exportSession.status == .Failed {
                    print("Export failed - \(exportSession.error)")
                }

                completion(concatenatedFile: nil)
                return
            }
        }
    }
}