Skip to content

Instantly share code, notes, and snippets.

@campionfellin
Created July 10, 2020 14:50
Show Gist options
  • Save campionfellin/0ab6c0f14f36b5bb802a203c83817513 to your computer and use it in GitHub Desktop.
Save campionfellin/0ab6c0f14f36b5bb802a203c83817513 to your computer and use it in GitHub Desktop.
import Foundation
import Foundation
import AVFoundation
class AudioSplitter {
var filePrepend: String = "file://"
var fileSeparator: Character = "."
var fileSplitAppend: String = "-split-"
func splitAudio(asset: AVAsset, segment: Int, splitSourceFileURL: Array<Substring>) {
// Create an output exporter (hardcoded to m4a)
let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A)!
exporter.outputFileType = AVFileType.m4a
// Only export for within this time range
let startTime = CMTimeMake(value: Int64(5 * 60 * segment), timescale: 1)
let endTime = CMTimeMake(value: Int64(5 * 60 * (segment+1)), timescale: 1)
exporter.timeRange = CMTimeRangeFromTimeToTime(start: startTime, end: endTime)
/**
Output file format:
originalFile-split-1.m4a
originalFile-split-2.m4a
Etc...
*/
let outputFileURL = URL(string: "\(filePrepend)\(splitSourceFileURL[0])\(fileSplitAppend)\(segment)\(fileSeparator)\(splitSourceFileURL[1])")!
exporter.outputURL = outputFileURL
// Do the export
exporter.exportAsynchronously(completionHandler: {
switch exporter.status {
case AVAssetExportSession.Status.failed:
print("Export failed.")
if let e = exporter.error {
print(e)
}
case AVAssetExportSession.Status.cancelled:
print("Export cancelled.")
default:
print("Export complete.")
}
})
return
}
public func processAudio(sourceFileURL: String) {
// Original file as URL
let fileURL: URL = URL(string: "\(filePrepend)\(sourceFileURL)")!
// Original file as AVAsset
let asset: AVAsset = AVAsset(url: fileURL)
let splitSourceFileURL = sourceFileURL.split(separator: fileSeparator)
// Length of original file
let duration = CMTimeGetSeconds(asset.duration)
let numOfSegments = Int(ceil(duration / 300) - 1)
for index in 0...numOfSegments {
splitAudio(asset: asset, segment: index, splitSourceFileURL: splitSourceFileURL)
}
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment