簡體   English   中英

快速添加或連接音頻文件

[英]append or concatenate audio files in swift

嗨,我想附加語音文件。

我正在使用AVAudioRecorder錄制語音,但是要播放錄音,我需要叫“停止”,但是在播放之后,我想繼續錄音。 就像本地的iOS語音備忘錄應用一樣。

我應該使用AVMutableCompositionTrack嗎?如何快速使用? 謝謝!

如果您只是想暫停錄音並在以后繼續錄音,可以使用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
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM