Tyrrrz / YoutubeExplode

Abstraction layer over YouTube's internal API
MIT License
2.95k stars 493 forks source link

How to download just the audiostream as an mp3? #23

Closed ShaiPreter closed 7 years ago

ShaiPreter commented 7 years ago

I understand that this library takes both the video and audio streams and then mixes them together to download a video. How can I do it so that it just downloads the audiostream?

SlowLogicBoy commented 7 years ago
var client = new YoutubeClient();
var info = await client.GetVideoInfoAsync(video.Id);
var audioStream = info?.AudioStreams?.OrderBy(s => s.Bitrate)?.Last();
using (var input = await client.GetMediaStreamAsync(audioStream))
using (var output = File.Create(fileName))
      await input.CopyToAsync(output);

This will most likely download .webm you will need to convert from .webm to .mp3 yourself https://github.com/Tyrrrz/YoutubeExplode/wiki/Usage-examples#download-media-stream

Tyrrrz commented 7 years ago

@ShaiPreter It doesn't mix them on its own, that's a huge task which is definitely out of scope. You can use ffmpeg via command line interface to do it though, if you need to. You can get metadata for separated media streams by accessing either the VideoStreams or AudioStreams collections on VideoInfo. The MixedStreams collection is for legacy video types that didn't have separate media.

@SlowLogicBoy Btw, you don't need to check info and info.AudioStreams for null as they are guaranteed to never be null. In fact, all public properties are guaranteed to not be null. :) You may want to use LastOrDefault() though, because if the video is muted it won't have any audio streams.

The returned audio stream can be in various formats, not just .webm, however neither of them is .mp3. To get the extension you can use streamInfo.Container.GetFileExtension(). Again, you can use ffmpeg to convert between formats.

Tyrrrz commented 7 years ago

@ShaiPreter example project for you, in case you are still interested https://github.com/Tyrrrz/YoutubeMusicDownloader