2016-04-12 5 views
1

私は次のコードで2つのオーディオファイルを連結しようとして失敗します。オーディオ輸出は、iOSスウィフトが

func concatenateFiles(audioFiles: [NSURL], completion: (concatenatedFile: NSURL?) ->()) { 
    // Result file 
    var nextClipStartTime = kCMTimeZero 
    let composition = AVMutableComposition() 
    let track = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid) 

    // Add each track 
    for audio in audioFiles { 
     let asset = AVURLAsset(URL: NSURL(fileURLWithPath: audio.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("\(stringFromDate(NSDate())).m4a") { 
      // 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 = fileURL 
      exportSession.outputFileType = AVFileTypeAppleM4A 
      // Perform the export 
      exportSession.exportAsynchronouslyWithCompletionHandler() { handler -> Void in 
       if exportSession.status == .Completed { 
        print("Export complete") 
        dispatch_async(dispatch_get_main_queue(), { 
         completion(concatenatedFile: fileURL) 
        }) 
        return 
       } else if exportSession.status == .Failed { 
        print("Export failed - \(exportSession.error)") 
       } 

       completion(concatenatedFile: nil) 
       return 
      } 
     } 
    } 
} 

しかし、私は、ファイルのエクスポートこのエラーを受け取りました:私はしました

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

をフォーマットを変えようとすると動作しませんが、私はもう考えていません。 何か助けてもらえますか? 、

+0

なぜあなたはここにパススループリセットを使用しようとしていますか? – matt

+0

申し訳ありませんが、私もこれを変更しました、正しいはAVAssetExportPresetAppleM4Aです –

答えて

0

私は本当に理由を知りませんが、私はexportSessionにoutputURLの帰属を変更すると問題が解決した

前:今

exportSession.outputURL = fileURL 

exportSession.outputURL = NSURL.fileURLWithPath(fileURL.path!) 
+0

確かに、あなたが行っていたように "手で" URLを形成することは、有効なファイルURLを作成しないためです。 – matt