YouTubeKit icon indicating copy to clipboard operation
YouTubeKit copied to clipboard

Getting only audio to file/AssetReader ?

Open chnbr opened this issue 1 year ago • 6 comments
trafficstars

I need to extract the audio part and save it to a file. Currently my code works like this:

// get the stream
let stream = try await YouTube(url: inUrl).streams
  .filterAudioOnly()
  .filter { $0.fileExtension == .m4a }
  .highestAudioBitrateStream()

// download stream url to locale file
(localeUrl, _) = try await URLSession.shared.download(from: stream?.url, delegate: self)

// copy downloaded file to mpeg4audio conforming file
let copyURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("tmpfile", conformingTo: .mpeg4Audio)
try? FileManager.default.removeItem(at: copyURL)
try FileManager.default.moveItem(at: localeUrl, to: copyURL)

// use AssetReader to read it
let asset = AVURLAsset(url: copyURL)
let assetReader = try AVAssetReader(asset: asset)

Now my problem is that I am restricting to m4a audio files which I don't want to. However, if I remove the filter modifier I can get audio which is not coded in MPEG4 audio. Obviously I can't copy such a file with "conformingTo: .mpeg4audio".

How can I download ALL audio coding types and feed this into AssetReader ? (I think AssetReader needs a correct file extension to work properly. How do I get the audio coding file type of a correct filetype extension for the stream ?)

Thanks !

chnbr avatar Nov 14 '24 06:11 chnbr