2015-03-31 56 views
1

嗨,我想追加語音文件。快速追加或連接音頻文件

我錄製語音與AVAudioRecorder,但打我需要調用「停止」的記錄,但打它後,我想繼續記錄。就像本機iOS語音備忘錄應用程序一樣。

我應該使用AVMutableCompositionTrack,我該如何在swift中做到這一點?謝謝!

回答

3

如果您正在尋找簡單地暫停錄音,並繼續它後,你可以使用AVAudioRecorder的暫停()函數,而不是停止(),當您使用播放()再次將繼續錄製。

但是,如果你正在尋找真正串聯音頻文件,你可以做這樣的:

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 
      } 
     } 
    } 
}