Skip to content

IcySnex/YouTubeMusicAPI

Repository files navigation

YouTube Music Icon YouTubeMusicAPI

YouTubeMusicAPI is a simple and efficient C# wrapper for the YouTube Music Web API, enabling easy search and retrieval of songs, videos, albums, artists, podcasts, and more. It also provides streaming data and access to an authenticated user's library, all with minimal effort.


⚠️ Major Update in Progress: v4 Recode

A complete overhaul of YouTubeMusicAPI is currently underway!

Originally, this library wasn’t intended to be a fully-fledged API wrapper for YouTube Music. My goal was only to implement basic search functionality so I could add yet another platform to my multi-music downloader, Melora.

This recode is my effort to turn YouTubeMusicAPI into a clean, consistent, and fully-featured API wrapper that does justice to everything YouTube Music has to offer - including library management, more detailed information, playback support, and explore endpoints - all while improving performance, efficiency, and code maintainability.

📌 You can track development progress in the recode branch and view planned features in the Project Board.


Getting Started

To install YouTubeMusicAPI, add the following package to your project:

dotnet add package YouTubeMusicAPI

To start using YouTube Music in your project, just create a new YouTubeMusicClient.

YouTubeMusicClient client = new(logger, geographicalLocation, visitorData, poToken, cookies);

Usage

Search

// Search for songs directly
PaginatedAsyncEnumerable<SearchResult> searchResults = client.SearchAsync(query, SearchCategory.Songs);
IReadOnlyList<SearchResult> bufferedSearchResults = await searchResults.FetchItemsAsync(0, 20);

foreach (SongSearchResult song in bufferedSearchResults.Cast<SongSearchResult>())
  Console.WriteLine($"{song.Name}, {string.Join(", ", song.Artists.Select(artist => artist.Name))} - {song.Album.Name}");

Getting more information

// Song/Video
SongVideoInfo info = await client.GetSongVideoInfoAsync(id);

Console.WriteLine($"{info.Name}, {string.Join(", ", info.Artists.Select(artist => artist.Name))} - {info.Description}");
// Album
string browseId = await client.GetAlbumBrowseIdAsync(id);
AlbumInfo info = await client.GetAlbumInfoAsync(browseId);

foreach (AlbumSongInfo song in info.Songs)
  Console.WriteLine($"{song.Name}, {song.SongNumber}/{info.SongCount}");
// Community Playlist
string browseId = client.GetCommunityPlaylistBrowseId(id);
CommunityPlaylistInfo info = await client.GetCommunityPlaylistInfoAsync(browseId);

Console.WriteLine($"{info.Name}, {info.SongCount} songs, {info.Description}");

// Community Playlist Songs
PaginatedAsyncEnumerable<CommunityPlaylistSong> playlistSongs = client.GetCommunityPlaylistSongsAsync(browseId);
IReadOnlyList<CommunityPlaylistSong> bufferedPlaylistSongs = await playlistSongs.FetchItemsAsync(0, 20);

foreach (CommunityPlaylistSongInfo song in bufferedPlaylistSongs)
  Console.WriteLine($"{song.Name}, {string.Join(", ", song.Artists.Select(artist => artist.Name))} - {song.Album?.Name}");
// Artist
ArtistInfo info = await client.GetArtistInfoAsync(id);

foreach (ArtistSongInfo song in info.Songs)
  Console.WriteLine($"{song.Name}, {string.Join(", ", song.Artists.Select(artist => artist.Name))} - {song.Album?.Name}");

Streaming & Downloading

In some cases (e.g. when using cookie authentication), getting streaming URLs requires deciphering. Sometimes, YouTube also enforces a "Proof of Origin Token" (PoToken), which is generated by an Anti-Bot-System.

PoToken generation requires JavaScript execution and a full DOM, which isn't feasible in a pure .NET environment. While JavaScript execution can be handled using interpreters like Jint, a full browser engine (e.g. Puppeteer, CefSharp) is required to generate the token.

To avoid this, PoTokens are not automatically generated by this library. However, you can manually provide a valid token using the YouTubeMusicClient constructor when necessary. You may use the IcySnex/YouTubeSessionGenerator library to generate valid visitorData and a poToken using C# (and a dependency on Node.js).

⚠️ Note:

It may occurr that you get a 403 Forbidden error when trying to get streaming data. This is usually caused by YouTube flagging your IP-Address as suspicious, e.g. when using a VPN or spaming the API in the past. You are then required to provide cookie authentication and a poToken to testify your request "comes from a valid client".

// Getting streaming data of a song
StreamingData streamingData = await client.GetStreamingDataAsync(id);

Console.WriteLine($"Expires in: {streamingData.ExpiresIn}");
Console.WriteLine($"Hls Manifest URL: {streamingData.HlsManifestUrl}");

foreach(MediaStreamInfo streamInfo in streamingData.StreamInfo)
{
  if (streamInfo is VideoStreamInfo videoStreamInfo)
    Console.WriteLine($"Video ({videoStreamInfo.Quality}): {videoStreamInfo.Url}");
  else if (streamInfo is AudioStreamInfo audioStreamInfo)
    Console.WriteLine($"Audio ({audioStreamInfo.SampleRate}): {audioStreamInfo.Url}");
}
// Download highest quality audio stream
StreamingData streamingData = await client.GetStreamingDataAsync(id);

MediaStreamInfo highestAudioStreamInfo = streamingData.StreamInfo
  .OfType<AudioStreamInfo>()
  .OrderByDescending(info => info.Bitrate)
  .First();
Stream stream = await highestAudioStreamInfo.GetStreamAsync();

using FileStream fileStream = new("audio.m4a", FileMode.Create, FileAccess.Write);
await stream.CopyToAsync(fileStream);

Access to a user's library

In order to access a user's library you first need to authenticate the user by using pre-authenticated cookies.

To obtain the necessary cookies, you'll need to present the official YouTube Music login page to your users. You could use an embedded browser like WebView2 in your application and then extract the cookies for the site ".youtube.com".

// Get saved/created community playlists
IEnumerable<LibraryCommunityPlaylist> communityPlaylists = await client.GetLibraryCommunityPlaylistsAsync();

foreach (LibraryCommunityPlaylist playlist in communityPlaylists)
  Console.WriteLine($"{playlist.Name}, {playlist.SongCount} songs");
// Get saved songs
IEnumerable<LibrarySong> songs = await client.GetLibrarySongsAsync();

foreach (LibrarySong song in songs)
  Console.WriteLine($"{song.Name}, {string.Join(", ", song.Artists.Select(artist => artist.Name))} - {song.Album.Name}");
// Get saved albums
IEnumerable<LibraryAlbum> albums = await client.GetLibraryAlbumsAsync();

foreach (LibraryAlbum album in albums)
  Console.WriteLine($"{album.Name}, {album.ReleaseYear}");
// Get artists with saved songs
IEnumerable<LibraryArtist> artists = await client.GetLibraryArtistsAsync();

foreach (LibraryArtist artist in artists)
  Console.WriteLine($"{artist.Name}, {artist.SongCount} saved songs");
// Get subscribed artists
IEnumerable<LibrarySubscription> subscriptions = await client.GetLibrarySubscriptionsAsync();

foreach (LibrarySubscription subscription in subscriptions)
  Console.WriteLine($"{subscription.Name}, {subscription.SubscribersInfo}");
// Get saved podcasts
IEnumerable<LibraryPodcast> podcasts = await client.GetLibraryPodcastsAsync();

foreach (LibraryPodcast podcast in podcasts)
  Console.WriteLine($"{podcast.Name}, {podcast.Host.Name}");

License

This project is licensed under the GNU General Public License v3.0. See the LICENSE file for details.


Contact

For questions, suggestions or problems, please open an issue with a detailed description.

About

YouTube Music Web API Wrapper for C#

Resources

License

Stars

Watchers

Forks

Contributors

Languages