Search code examples
c#bytevideo-library

How can I download a video using VideoLib when it's Async?


Alright, here is my dilemma:

I wanted to learn how to use NuGet, so I tested it out using a system called VideoLibrary(https://www.nuget.org/packages/VideoLibrary/). I successfully got it installed to my computer, and was finally got it working inside of code. I was able to successfully download a video, which is the purpose of the extension, however it was in the wrong format. So, having read through the questions and answers section, I got this code:

        var youTube = YouTube.Default;
        var allVideos = await youTube.GetAllVideosAsync(URL);
        var mp4Videos = allVideos.Where(_ => _.Format == VideoFormat.Mp4);

Now, from what my understanding is, that first downloads all the videos, and then sets the variable to only the MP4 video. However, after that is done, I don't know how to save it to a byte array. Typically, to save a video using VideoLib, you have to assign it to a byte array and then save the byte array to a file. So I used this code previously with a video that wasn't async:

byte[] bytes = video.GetBytes();
var stream = video.Stream();
File.WriteAllBytes(@"C:\" + fullName, bytes);

Now, this method doesn't work with my videos now because they're async. THe developer mentioned later that you could assign the video to a byte array by using:

byte[] bytes = allVideos.GetBytesAsync();

However, that doesn't work for some reason. I'm assuming I'm using it wrong and that's why, but I don't know. The code is underlined in red, and it gives:

'IEnumerable<YouTubeVideo>' does not contain a definition to 'GetBytesAsync' 
and no extension method 'GetBytesAsync accepting a first argument of type 
'IEnumerable<YouTubeVideo>'coulb be found

Any help would be appreciated.


Solution

  • Okay, so, I've discovered the answer to my question:

    The problem is that allVideos is multiple videos. When you use the method GetAllVideosAsync it retrieves a whole list of videos. You have to narrow it down.

    When you use mp4Videos you've narrowed it down to one video, however the computer still doesn't know that because it's a variable of multiple videos. So, simply put the code through this:

    var SingleVideo = mp4Videos.FirstOrDefault();
    

    Then, using the SingleVideo variable, you can save it to a byte array like a conventional video, but using the async method:

    Byte[] Byte = await SingleVideo.GetBytesAsync();
    

    Once the contents are saved to the byte array, you can save it any way you please.

    I hope this helps anyone who needs it!