I am trying to use AVAssetExportSession
to export audio form video but every time I try it, it fails and I don't know why ?!
this is the code
import AVFoundation
protocol AudioExtractionProtocol {
func extractAudio(from fileUrl: URL, to outputUrl: URL)
}
final class AudioExtraction {
private var avAsset: AVAsset?
private var avAssetExportSession: AVAssetExportSession?
init() {}
}
//MARK: - AudioExtraction conforms to AudioExtractionProtocol
extension AudioExtraction: AudioExtractionProtocol {
func extractAudio(from fileUrl: URL, to outputUrl: URL) {
createAVAsset(for: fileUrl)
createAVAssetExportSession(for: outputUrl)
exportAudio()
}
}
//MARK: - Private Methods
extension AudioExtraction {
private func createAVAsset(for fileUrl: URL) {
avAsset = AVAsset(url: fileUrl)
}
private func createAVAssetExportSession(for outputUrl: URL) {
guard let avAsset else { return }
avAssetExportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetAppleM4A)
avAssetExportSession?.outputURL = outputUrl
}
private func exportAudio() {
guard let avAssetExportSession else { return }
print("I am here \n")
avAssetExportSession.exportAsynchronously {
if avAssetExportSession.status == .failed {
print("\(avAssetExportSession.status)\n")
}
}
}
}
func test_AudioExtraction_extractAudioAndWriteItToFile() {
let videoUrl = URL(string: "https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4")!
let audioExtraction: AudioExtractionProtocol = AudioExtraction()
audioExtraction.extractAudio(from: videoUrl, to: FileMangerTest.audioFile)
FileMangerTest.tearDown()
}
class FileMangerTest {
private static let fileManger = FileManager.default
private static var directoryUrl: URL {
fileManger.urls(for: .cachesDirectory, in: .userDomainMask).first!
}
static var audioFile: URL {
directoryUrl.appendingPathComponent("audio", conformingTo: .mpeg4Audio)
}
static func tearDown() {
try? fileManger.removeItem(at: audioFile)
}
static func contant(at url: URL) -> Data? {
return fileManger.contents(atPath: url.absoluteString)
}
}