### Install YouTube Go Library Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Install the YouTube Go library using the go get command. ```bash go get github.com/kkdai/youtube/v2 ``` -------------------------------- ### GetVideo Example Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Example of how to use the GetVideo method to fetch video metadata and print its title and duration. Ensure the youtube package is imported. ```go client := &youtube.Client{} video, err := client.GetVideo("https://www.youtube.com/watch?v=dQw4w9WgXcQ") if err != nil { panic(err) } fmt.Printf("Title: %s\n", video.Title) fmt.Printf("Duration: %v\n", video.Duration) ``` -------------------------------- ### GetStream Example Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Example of downloading a video stream using GetStream. It fetches video metadata, selects a format, downloads the stream, and saves it to a file. Remember to close the stream and file. ```go client := &youtube.Client{} video, _ := client.GetVideo("dQw4w9WgXcQ") formats := video.Formats.WithAudioChannels() stream, size, err := client.GetStream(video, &formats[0]) if err != nil { panic(err) } defer stream.Close() file, _ := os.Create("video.mp4") defer file.Close() io.Copy(file, stream) fmt.Printf("Downloaded %d bytes\n", size) ``` -------------------------------- ### GetVideoContext Example Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Example demonstrating the use of GetVideoContext with a 30-second timeout. This method is useful for controlling request lifecycles. ```go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() client := &youtube.Client{} video, err := client.GetVideoContext(ctx, "dQw4w9WgXcQ") if err != nil { panic(err) } ``` -------------------------------- ### Install youtubedr via Go Source: https://github.com/kkdai/youtube/blob/master/README.md Install the youtubedr command-line tool using Go. Ensure you have Go version 1.26 or later installed. ```shell go install github.com/kkdai/youtube/v2/cmd/youtubedr@latest ``` -------------------------------- ### Listing Available Formats Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Utilities.md Example code demonstrating how to list and display details of all available video formats, including quality, MIME type, resolution, bitrate, and audio channels. ```APIDOC ## Listing Available Formats ```go video, _ := client.GetVideo("videoID") for i, format := range video.Formats { fmt.Printf("%d. Quality: %s\n", i, format.QualityLabel) fmt.Printf(" Type: %s\n", format.MimeType) fmt.Printf(" Resolution: %dx%d\n", format.Width, format.Height) fmt.Printf(" Bitrate: %d\n", format.Bitrate) fmt.Printf(" Audio: %d channels\n", format.AudioChannels) } ``` ``` -------------------------------- ### Get Video with Context Timeout Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Demonstrates how to fetch video information with a specified timeout using context. Use this to prevent long-running requests. ```go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) deffer cancel() video, err := client.GetVideoContext(ctx, videoID) if err == context.DeadlineExceeded { log.Println("Request timed out") } ``` -------------------------------- ### Get Playlist with Context Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Fetches playlist metadata and video entries with context support for managing the request lifecycle. ```go func (c *Client) GetPlaylistContext(ctx context.Context, url string) (*Playlist, error) ``` -------------------------------- ### Search Transcript for Keywords Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Transcript.md Provides an example of how to search through a video's transcript for specific keywords, ignoring case. ```APIDOC ## Search Transcript for Keywords ### Description Searches through the video transcript for occurrences of a specified keyword, performing a case-insensitive comparison. ### Usage ```go transcript, _ := client.GetTranscript(video, "en") searchTerm := "important" fmt.Printf("Occurrences of '%s':\n", searchTerm) for _, segment := range transcript { if strings.Contains(strings.ToLower(segment.Text), strings.ToLower(searchTerm)) { fmt.Printf(" [%s] %s\n", segment.OffsetText, segment.Text) } } ``` ``` -------------------------------- ### Downloader.DownloadComposite Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Downloader.md Downloads video and audio streams separately and merges them using ffmpeg. Requires ffmpeg to be installed. ```APIDOC ## Downloader.DownloadComposite ### Description Downloads video and audio streams separately and merges them using ffmpeg. Requires ffmpeg to be installed and in system PATH. ### Method `func (dl *Downloader) DownloadComposite(ctx context.Context, outputFile string, v *youtube.Video, quality string, mimetype string, language string) error` ### Parameters #### Path Parameters - **ctx** (*context.Context*) - Required - Context for managing download lifecycle - **outputFile** (*string*) - Optional - Output filename. If empty, uses video title - **v** (*youtube.Video*) - Required - Video object from Client.GetVideo() - **quality** (*string*) - Required - Quality to download (e.g., "720p", "1080p", "22" for itag) - **mimetype** (*string*) - Optional - MIME type filter for video (e.g., "mp4", "webm"). Empty means any type - **language** (*string*) - Optional - Audio language to select. Empty means first available audio ### Return Type - `error` — Error if download or ffmpeg merge fails ### Requirements - ffmpeg must be installed and in system PATH - Used for high-quality downloads where you want to select video and audio separately ### Example ```go dl := &downloader.Downloader{ OutputDir: "./downloads", } video, _ := dl.GetVideo("dQw4w9WgXcQ") // Download best 1080p video with English audio err := dl.DownloadComposite( context.Background(), "", // Use video title video, "1080p", // Quality "mp4", // MIME type preference "English", // Audio language ) if err != nil { panic(err) } ``` ``` -------------------------------- ### Selecting Video Formats Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Provides examples of filtering and selecting specific video formats based on quality, audio presence, and type (e.g., MP4). ```go // Get 720p with audio formats := video.Formats.Quality("720p").WithAudioChannels() // Get MP4 video-only formats := video.Formats.Type("mp4").AudioChannels(0) // Sort and get best formats.Sort() best := formats[0] ``` -------------------------------- ### Set Log Level Programmatically Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Programmatically change the log level for the library. This example sets the level to 'debug' and demonstrates that debug logs will be printed. ```go import "github.com/kkdai/youtube/v2" youtube.SetLogLevel("debug") client := &youtube.Client{} video, _ := client.GetVideo("dQw4w9WgXcQ") // Debug logs will be printed to stderr ``` -------------------------------- ### Set Default Client to Android Client Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Change the default client used by the library to the Android client. This can affect format selection and other request behaviors. This example sets the default client and then uses it to fetch a video. ```go // Use Android client for better format selection youtube.DefaultClient = youtube.AndroidClient client := &youtube.Client{} video, _ := client.GetVideo("dQw4w9WgXcQ") // Now uses AndroidClient ``` -------------------------------- ### Common Format Download Patterns Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Format.md Demonstrates common patterns for downloading video formats, including getting the best quality with audio, specific qualities, separating video and audio, and filtering by MIME type. ```go client := &youtube.Client{} video, _ := client.GetVideo("dQw4w9WgXcQ") formats := video.Formats.WithAudioChannels() formats.Sort() stream, _, _ := client.GetStream(video, &formats[0]) formats = video.Formats.Quality("720p") if len(formats) > 0 { formats.Sort() stream, _, _ := client.GetStream(video, &formats[0]) } videoFormats := video.Formats.Type("video").AudioChannels(0) audioFormats := video.Formats.Type("audio").WithAudioChannels() videoFormats.Sort() audioFormats.Sort() mp4Formats := video.Formats.Type("mp4") webmFormats := video.Formats.Type("webm") ``` -------------------------------- ### Access Global Logger Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Access the global structured logger directly for custom logging messages. This example shows how to log info, debug, and error messages. ```go youtube.Logger.Info("Custom message", "videoID", "dQw4w9WgXcQ") youtube.Logger.Debug("Debug info", "key", "value") youtube.Logger.Error("Error occurred", "error", err) ``` -------------------------------- ### Download and Merge Video/Audio Streams Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Downloader.md Use this method when you need to download the best quality video and audio streams separately and then merge them into a single file using ffmpeg. Requires ffmpeg to be installed and in the system PATH. You can specify quality, MIME type, and audio language preferences. ```Go dl := &downloader.Downloader{ OutputDir: "./downloads", } video, _ := dl.GetVideo("dQw4w9WgXcQ") // Download best 1080p video with English audio err := dl.DownloadComposite( context.Background(), "", // Use video title video, "1080p", // Quality "mp4", // MIME type preference "English", // Audio language ) if err != nil { panic(err) } ``` -------------------------------- ### Work with Playlists Source: https://github.com/kkdai/youtube/blob/master/_autodocs/INDEX.md Retrieves playlist details, including title and author, and iterates through its video entries. It also shows how to get full video metadata from a playlist entry for subsequent download. ```go client := &youtube.Client{} playlist, err := client.GetPlaylist("PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP") if err != nil { panic(err) } fmt.Printf("%s by %s\n", playlist.Title, playlist.Author) for i, entry := range playlist.Videos { fmt.Printf("%d. %s (%v)\n", i+1, entry.Title, entry.Duration) // Get full video metadata for download video, err := client.VideoFromPlaylistEntry(entry) if err != nil { continue } // Download... } ``` -------------------------------- ### Get Stream URL with Context Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Retrieves the download URL for a specific format with context support, allowing for request lifecycle management. ```go func (c *Client) GetStreamURLContext(ctx context.Context, video *Video, format *Format) (string, error) ``` -------------------------------- ### High-Quality Composite Download Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Downloader.md Downloads a video in a specific resolution and format, combining video and audio streams. This method requires FFmpeg to be installed on the system. ```Go video, _ := dl.GetVideo("dQw4w9WgXcQ") // Download best 1080p video with English audio // This requires ffmpeg installed err := dl.DownloadComposite( context.Background(), "my-video.mp4", video, "1080p", "mp4", "English", ) if err != nil { println("Error:", err) } ``` -------------------------------- ### Download YouTube Video with Specific Quality Source: https://github.com/kkdai/youtube/blob/master/README.md Download a YouTube video by specifying the desired quality (e.g., 'medium', 'hd720', 'hd1080'). For 'hd1080' and higher, ffmpeg installation is necessary. ```shell ffmpeg //check ffmpeg is installed, if not please download ffmpeg and set to your PATH. youtubedr download -q hd1080 https://www.youtube.com/watch?v=rFejpH_tAHM ``` ```shell youtubedr download -q medium https://www.youtube.com/watch?v=rFejpH_tAHM ``` -------------------------------- ### Get Playlist Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Fetches playlist metadata and its associated video entries using a playlist URL or ID. Handles playlist extraction and potential errors. ```go func (c *Client) GetPlaylist(url string) (*Playlist, error) ``` ```go client := &youtube.Client{} playlist, err := client.GetPlaylist("PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP") if err != nil { panic(err) } fmt.Printf("Playlist: %s by %s\n", playlist.Title, playlist.Author) for i, video := range playlist.Videos { fmt.Printf("%d. %s\n", i+1, video.Title) } ``` -------------------------------- ### Get Video Transcript in Multiple Languages (Fallback) Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Transcript.md Fetches a video transcript, trying a list of languages in order and falling back if none are found. Requires the video ID and a list of desired language codes. ```go video, _ := client.GetVideo("dQw4w9WgXcQ") languages := []string{"en", "es", "fr", "de"} var transcript youtube.VideoTranscript var err error for _, lang := range languages { transcript, err = client.GetTranscript(video, lang) if err == nil { fmt.Printf("Got transcript in: %s\n", lang) break } } if err != nil { fmt.Println("No transcript available") } ``` -------------------------------- ### Configure Download Chunk Size Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Configure the size of download chunks in bytes. Larger chunks reduce request count but increase memory per goroutine. Smaller chunks increase request count but lower memory usage. This example sets chunks to 1 MB. ```go client := &youtube.Client{ ChunkSize: youtube.Size1Mb, // 1 MB chunks } // Or custom size client.ChunkSize = 5 * 1024 * 1024 // 5 MB ``` -------------------------------- ### Get and Print Video Transcript Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Shows how to retrieve the transcript for a video in a specific language. It handles cases where transcripts are disabled and demonstrates printing the full transcript or iterating through segments. ```go video, _ := client.GetVideo(videoID) transcript, err := client.GetTranscript(video, "en") if err == youtube.ErrTranscriptDisabled { fmt.Println("No transcript available") return } // Print all segments fmt.Println(transcript.String()) // Or iterate for _, segment := range transcript { fmt.Printf("[%s] %s\n", segment.OffsetText, segment.Text) } ``` -------------------------------- ### Set Log Level via Environment Variable Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Set the log level for all library output using the LOGLEVEL environment variable. This example sets the level to 'debug'. ```bash # Set log level to debug export LOGLEVEL=debug go run myapp.go # Or set in code os.Setenv("LOGLEVEL", "debug") ``` -------------------------------- ### Set Max Concurrent Download Routines Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Control the maximum number of concurrent goroutines for parallel downloads. Higher values download faster but use more resources. This example sets the limit to 20. ```go client := &youtube.Client{ MaxRoutines: 20, // 20 parallel downloads } video, _ := client.GetVideo("dQw4w9WgXcQ") stream, _, _ := client.GetStream(video, &video.Formats[0]) // Download will use up to 20 concurrent goroutines ``` -------------------------------- ### Get Video Metadata from Playlist Entry Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Retrieves full video metadata for a given playlist entry. Use this when you have a PlaylistEntry object and need to fetch the complete video details. ```Go func (c *Client) VideoFromPlaylistEntry(entry *PlaylistEntry) (*Video, error) ``` ```Go playlist, _ := client.GetPlaylist("PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP") firstEntry := playlist.Videos[0] video, err := client.VideoFromPlaylistEntry(firstEntry) if err != nil { panic(err) } // Now video has all formats and can be downloaded ``` -------------------------------- ### YouTube Client Configuration Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Initializes a YouTube client with custom configurations for HTTP client, maximum routines, and chunk size. ```go client := &youtube.Client{ HTTPClient: nil, // Use default or custom HTTP client MaxRoutines: 10, // Parallel download goroutines ChunkSize: 10 * 1024 * 1024, // 10 MB chunks } ``` -------------------------------- ### Android Client Configuration Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Recommended client for downloads. Offers good format selection and stability. ```go var AndroidClient = ClientInfo{ Name: "ANDROID", Version: "20.10.38", Key: "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w", UserAgent: "com.google.android.youtube/20.10.38 (Linux; U; Android 11) gzip", } ``` -------------------------------- ### Configure YouTube Client Source: https://github.com/kkdai/youtube/blob/master/_autodocs/INDEX.md Shows how to configure the YouTube client by setting HTTP client timeouts, maximum concurrent routines for faster downloads, and chunk sizes for downloads. It also demonstrates setting the log level. ```go client := &youtube.Client{ HTTPClient: &http.Client{ Timeout: 30 * time.Second, }, MaxRoutines: 20, // Faster downloads ChunkSize: 50 * 1024 * 1024, // 50 MB chunks } // Or programmatically youtube.SetLogLevel("debug") ``` -------------------------------- ### Configure Client for Fast Downloads Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Sets a high number of routines and large chunk size for optimizing download speeds. ```go client := &youtube.Client{ MaxRoutines: 50, ChunkSize: 50 * 1024 * 1024, // 50 MB chunks } ``` -------------------------------- ### Get Video Transcript Source: https://github.com/kkdai/youtube/blob/master/_autodocs/INDEX.md Retrieves the transcript for a given YouTube video in a specified language. Handles cases where transcripts are disabled. ```APIDOC ## GetTranscript ### Description Retrieves the transcript for a video in a specified language. ### Method ``` client.GetTranscript(video *youtube.Video, language string) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go client := &youtube.Client{} video, _ := client.GetVideo("dQw4w9WgXcQ") transcript, err := client.GetTranscript(video, "en") ``` ### Response #### Success Response (200) - **transcript** (*youtube.TranscriptList) - A list of transcript segments. - **err** (*error) - Error if fetching fails, potentially `youtube.ErrTranscriptDisabled`. #### Response Example ```go fmt.Println(transcript.String()) for _, segment := range transcript { fmt.Printf("[%s] %s\n", segment.OffsetText, segment.Text) } ``` ``` -------------------------------- ### Configure Client for Faster Downloads Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Adjust MaxRoutines and ChunkSize to potentially improve download speeds. Be mindful of YouTube's rate limiting. ```go // Increase parallelization client.MaxRoutines = 50 // Increase chunk size client.ChunkSize = 50 * 1024 * 1024 // Check format bitrate mt.Printf("Bitrate: %d\n", format.Bitrate) ``` -------------------------------- ### Sort Formats Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Format.md Sorts formats by resolution, FPS, codec, and bitrate. This is typically used after filtering to get the best available format. ```go video, _ := client.GetVideo("dQw4w9WgXcQ") formats := video.Formats.Quality("720p") formats.Sort() stream, _, _ := client.GetStream(video, &formats[0]) ``` -------------------------------- ### Configure YouTube Client with ClientInfo Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Demonstrates how to configure the YouTube client to use a specific client type, such as the WebClient. This affects the User-Agent and other request parameters. ```Go type ClientInfo struct { Name string Key string Version string UserAgent string AndroidVersion int DeviceModel string } ``` ```Go client := &youtube.Client{} client.client = &youtube.WebClient // Use web client instead of default video, _ := client.GetVideo("dQw4w9WgXcQ") ``` -------------------------------- ### Client Configuration for Download Speed Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Demonstrates how to configure the YouTube client's MaxRoutines and ChunkSize for optimizing download speeds. Use higher values for fast connections and lower values for slow connections. ```go // For fast downloads client := &youtube.Client{ MaxRoutines: 50, ChunkSize: 50 * 1024 * 1024, // 50 MB } // For slow/mobile client := &youtube.Client{ MaxRoutines: 3, ChunkSize: 512 * 1024, // 512 KB } ``` -------------------------------- ### VideoFromPlaylistEntryContext Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Gets full video metadata from a playlist entry with context support. This method allows for cancellation and timeouts via a context object. ```APIDOC ## VideoFromPlaylistEntryContext ### Description Gets full video metadata from a playlist entry with context support. This method allows for cancellation and timeouts via a context object. ### Method ```go func (c *Client) VideoFromPlaylistEntryContext(ctx context.Context, entry *PlaylistEntry) (*Video, error) ``` ### Parameters #### Path Parameters - **ctx** (`context.Context`) - Required - Context for request lifecycle - **entry** (`*PlaylistEntry`) - Required - Playlist entry ### Return Type - `*Video` — Fully populated Video metadata - `error` — Error if fetch fails ``` -------------------------------- ### YouTube Go Client Quick Reference Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md A comprehensive cheat sheet for using the YouTube Go client library. It covers common operations like client creation, video retrieval, format listing, downloading, playlist handling, and transcript fetching. ```go // Import import "github.com/kkdai/youtube/v2" import "github.com/kkdai/youtube/v2/downloader" // Create client client := &youtube.Client{} // Get video video, err := client.GetVideo(url) // List formats for _, f := range video.Formats { println(f.QualityLabel) } // Select and sort formats := video.Formats.Quality("720p").WithAudioChannels() formats.Sort() // Download stream stream, size, err := client.GetStream(video, &formats[0]) defer stream.Close() // Get URL url, err := client.GetStreamURL(video, &formats[0]) // Playlist playlist, err := client.GetPlaylist(playlistID) for _, entry := range playlist.Videos { video, _ := client.VideoFromPlaylistEntry(entry) } // Transcript transcript, err := client.GetTranscript(video, "en") // High-level download dl := &downloader.Downloader{OutputDir: "./videos"} dl.Download(ctx, video, &formats[0], "") // Error handling if errors.Is(err, youtube.ErrVideoPrivate) { println("Private video") } ``` -------------------------------- ### Programmatic Client Configuration Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Configure the YouTube client programmatically, including setting the log level and customizing HTTP client, MaxRoutines, and ChunkSize. ```go // Log level youtube.SetLogLevel("debug") // Client configuration client := &youtube.Client{ HTTPClient: customHTTPClient, MaxRoutines: 20, ChunkSize: 25 * 1024 * 1024, } ``` -------------------------------- ### Get Video Information Source: https://github.com/kkdai/youtube/blob/master/_autodocs/INDEX.md Retrieve metadata for a video without downloading the stream. This is useful for displaying video titles, durations, and available format counts. ```go video, _ := client.GetVideo("videoID") fmt.Printf("Title: %s\n", video.Title) fmt.Printf("Duration: %v\n", video.Duration) fmt.Printf("Formats available: %d\n", len(video.Formats)) ``` -------------------------------- ### VideoFromPlaylistEntry Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Gets full video metadata from a playlist entry. This method retrieves comprehensive video details based on a provided playlist entry object. ```APIDOC ## VideoFromPlaylistEntry ### Description Gets full video metadata from a playlist entry. This method retrieves comprehensive video details based on a provided playlist entry object. ### Method ```go func (c *Client) VideoFromPlaylistEntry(entry *PlaylistEntry) (*Video, error) ``` ### Parameters #### Path Parameters - **entry** (`*PlaylistEntry`) - Required - Playlist entry from a retrieved Playlist ### Return Type - `*Video` — Fully populated Video with all formats and metadata - `error` — Error if video fetch fails ### Example ```go playlist, _ := client.GetPlaylist("PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP") firstEntry := playlist.Videos[0] video, err := client.VideoFromPlaylistEntry(firstEntry) if err != nil { panic(err) } // Now video has all formats and can be downloaded ``` ``` -------------------------------- ### Search Transcript for Keywords Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Transcript.md Demonstrates how to search through a video transcript for specific keywords, ignoring case. Prints segments containing the search term. ```go transcript, _ := client.GetTranscript(video, "en") searchTerm := "important" fmt.Printf("Occurrences of '%s':\n", searchTerm) for _, segment := range transcript { if strings.Contains(strings.ToLower(segment.Text), strings.ToLower(searchTerm)) { fmt.Printf(" [%s] %s\n", segment.OffsetText, segment.Text) } } ``` -------------------------------- ### Get Stream with Context Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Retrieves a stream reader with context support for a specific video format. Use when you need to manage the request lifecycle with a context. ```go func (c *Client) GetStreamContext(ctx context.Context, video *Video, format *Format) (io.ReadCloser, int64, error) ``` ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() client := &youtube.Client{} video, _ := client.GetVideoContext(ctx, "dQw4w9WgXcQ") stream, _, _ := client.GetStreamContext(ctx, video, &video.Formats[0]) defer stream.Close() ``` -------------------------------- ### Playlist Operations with Context for Timeout Control Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Playlist.md Demonstrates how to use context with timeouts for fetching playlist data, retrieving video metadata, and downloading streams, ensuring operations do not exceed a specified duration. ```Go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() client := &youtube.Client{} playlist, err := client.GetPlaylistContext(ctx, "PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP") if err != nil { panic(err) } // Get first video with context firstEntry := playlist.Videos[0] video, err := client.VideoFromPlaylistEntryContext(ctx, firstEntry) if err != nil { panic(err) } // Download with context stream, _, _ := client.GetStreamContext(ctx, video, &video.Formats[0]) defer stream.Close() ``` -------------------------------- ### Web Client Configuration Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Browser-like client, suitable for age-restricted content but may require signature deciphering. ```go var WebClient = ClientInfo{ Name: "WEB", Version: "2.20220801.00.00", Key: "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8", UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", } ``` -------------------------------- ### Filter Formats by Audio Language Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Format.md Filters formats to include only those with a matching audio language display name. For example, to retrieve all English or Spanish audio tracks. ```go englishFormats := video.Formats.Language("English") spanishFormats := video.Formats.Language("Spanish") ``` -------------------------------- ### Find Best Quality Video Format Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Utilities.md Demonstrates two methods for finding the best quality video format: using `WithAudioChannels` and `Sort`, or a manual search based on height. ```go // Method 1: WithAudioChannels + Sort formats := video.Formats.WithAudioChannels() formats.Sort() best := formats[0] ``` ```go // Method 2: Manual search var best *youtube.Format for i := range video.Formats { if video.Formats[i].Height > best.Height { best = &video.Formats[i] } } ``` -------------------------------- ### Configure Client for Mobile/Low Bandwidth Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Sets a low number of routines and small chunk size for optimizing performance on mobile or low-bandwidth connections. ```go client := &youtube.Client{ MaxRoutines: 3, ChunkSize: 512 * 1024, // 512 KB chunks } ``` -------------------------------- ### Get Video Transcript Source: https://github.com/kkdai/youtube/blob/master/_autodocs/INDEX.md Fetches the transcript for a YouTube video in a specified language. It handles cases where transcripts are disabled and provides methods to iterate through transcript segments. ```go client := &youtube.Client{} video, _ := client.GetVideo("dQw4w9WgXcQ") transcript, err := client.GetTranscript(video, "en") if err != nil { if err == youtube.ErrTranscriptDisabled { fmt.Println("No transcript available") } return } // Print formatted transcript fmt.Println(transcript.String()) // Iterate segments for _, segment := range transcript { fmt.Printf("[%s] %s\n", segment.OffsetText, segment.Text) } ``` -------------------------------- ### Get YouTube Video Information Source: https://github.com/kkdai/youtube/blob/master/README.md Retrieve detailed information about a YouTube video, including its title, author, and available stream formats with their respective quality and codecs. ```shell youtubedr info https://www.youtube.com/watch?v=rFejpH_tAHM ``` -------------------------------- ### Retrieve and Display Basic Video Metadata Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Video.md Fetches a video using its URL and prints essential metadata such as title, author, duration, views, publish date, and description. ```go client := &youtube.Client{} video, err := client.GetVideo("https://www.youtube.com/watch?v=dQw4w9WgXcQ") if err != nil { panic(err) } fmt.Printf("Title: %s\n", video.Title) fmt.Printf("Author: %s\n", video.Author) fmt.Printf("Duration: %v\n", video.Duration) fmt.Printf("Views: %d\n", video.Views) fmt.Printf("Published: %s\n", video.PublishDate.Format("2006-01-02")) fmt.Printf("Description: %s\n", video.Description) ``` -------------------------------- ### Get Audio Language Display Name Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Utilities.md Retrieve the display name for the audio track language of a format. Returns an empty string if the format does not have multi-audio or a language is not specified. ```go video, _ := client.GetVideo("dQw4w9WgXcQ") for _, format := range video.Formats { if lang := format.LanguageDisplayName(); lang != "" { fmt.Printf("Format %d: %s audio\n", format.ItagNo, lang) } } ``` -------------------------------- ### Fetch and Display Full Transcript Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Transcript.md Demonstrates how to fetch a video's transcript in English and display it as a formatted string. Handles potential errors during fetching. ```go client := &youtube.Client{} video, err := client.GetVideo("dQw4w9WgXcQ") if err != nil { panic(err) } // Get English transcript transcript, err := client.GetTranscript(video, "en") if err != nil { panic(err) // Video may not have transcripts } // Display formatted transcript fmt.Println(transcript.String()) ``` -------------------------------- ### Group Video Formats by MIME Type Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Utilities.md Shows how to group video formats by their MIME type and print the count of formats for each type. Requires the `strings` and `fmt` packages. ```go // Group by MIME type groups := make(map[string]youtube.FormatList) for _, format := range video.Formats { mimeType := strings.Split(format.MimeType, ";")[0] groups[mimeType] = append(groups[mimeType], format) } for mimeType, formats := range groups { fmt.Printf("%s: %d formats\n", mimeType, len(formats)) } ``` -------------------------------- ### Import Paths for YouTube Package Source: https://github.com/kkdai/youtube/blob/master/_autodocs/INDEX.md Import the main youtube package for general functionality and the downloader subpackage for specific download operations. ```go // Main package import "github.com/kkdai/youtube/v2" // Downloader subpackage import "github.com/kkdai/youtube/v2/downloader" ``` -------------------------------- ### Basic File Download Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Downloader.md Downloads the best available quality video with audio. Ensure the output directory is set and handle potential errors during video retrieval and download. ```Go import ( "context" "github.com/kkdai/youtube/v2" "github.com/kkdai/youtube/v2/downloader" ) func main() { dl := &downloader.Downloader{ OutputDir: "./videos", } video, err := dl.GetVideo("dQw4w9WgXcQ") if err != nil { panic(err) } // Get best quality with audio formats := video.Formats.WithAudioChannels() formats.Sort() err = dl.Download(context.Background(), video, &formats[0], "") if err != nil { panic(err) } println("Downloaded successfully") } ``` -------------------------------- ### Get Stream URL Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Obtains the direct download URL for a specific video format without downloading the content. Useful for pre-fetching URLs or for use with external download managers. ```go func (c *Client) GetStreamURL(video *Video, format *Format) (string, error) ``` ```go client := &youtube.Client{} video, _ := client.GetVideo("dQw4w9WgXcQ") url, err := client.GetStreamURL(video, &video.Formats[0]) if err != nil { panic(err) } fmt.Printf("Download URL: %s\n", url) ``` -------------------------------- ### Batch Download from Playlist Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Downloader.md Downloads multiple videos from a YouTube playlist, attempting to get a 720p format for each. It includes error handling for individual video processing and download failures. ```Go playlist, _ := dl.GetPlaylist("PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP") for i, entry := range playlist.Videos { video, err := dl.VideoFromPlaylistEntry(entry) if err != nil { println("Skip:", entry.Title) continue } formats := video.Formats.Quality("720p").WithAudioChannels() if len(formats) == 0 { println("No 720p format:", video.Title) continue } formats.Sort() filename := fmt.Sprintf("%03d.mp4", i+1) err = dl.Download(context.Background(), video, &formats[0], filename) if err != nil { println("Error downloading:", entry.Title, err) } else { println("Downloaded:", filename) } } ``` -------------------------------- ### Download Best Available Quality Video Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Shows how to download the highest quality video stream that includes audio. It sorts available formats and then downloads the first one. ```go client := &youtube.Client{} video, _ := client.GetVideo(videoID) // Get formats with audio formats := video.Formats.WithAudioChannels() formats.Sort() // Sort by resolution, codec, bitrate // Download first (best) format stream, size, _ := client.GetStream(video, &formats[0]) deffer stream.Close() file, _ := os.Create("video.mp4") deffer file.Close() io.Copy(file, stream) ``` -------------------------------- ### Get Video Metadata from Playlist Entry with Context Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Client.md Retrieves full video metadata from a playlist entry, supporting context for request lifecycle management. This is useful for cancellable or timed requests. ```Go func (c *Client) VideoFromPlaylistEntryContext(ctx context.Context, entry *PlaylistEntry) (*Video, error) ``` -------------------------------- ### Configure Custom HTTP Client Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Sets a custom HTTP client with specific timeout and transport settings. ```go client := &youtube.Client{ HTTPClient: &http.Client{ Timeout: 60 * time.Second, Transport: &http.Transport{ MaxIdleConns: 20, }, }, } ``` -------------------------------- ### Get Audio Track Language Display Name Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Format.md Retrieves the display name of the audio track language for multi-audio formats. Returns an empty string if the format does not have multiple audio languages. ```go func (f *Format) LanguageDisplayName() string ``` ```go video, _ := client.GetVideo("dQw4w9WgXcQ") for _, format := range video.Formats { if lang := format.LanguageDisplayName(); lang != "" { fmt.Printf("Format %d: %s\n", format.ItagNo, lang) } } ``` -------------------------------- ### Download Specific Quality Video (720p) Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Illustrates how to filter and download a video in a specific quality, such as 720p. It sorts the filtered formats and selects the best available. ```go video, _ := client.GetVideo(videoID) // Filter to 720p formats := video.Formats.Quality("720p") if len(formats) == 0 { fmt.Println("720p not available") return } // Sort and select best codec formats.Sort() stream, _, _ := client.GetStream(video, &formats[0]) deffer stream.Close() ``` -------------------------------- ### Customize HTTP Client Transport Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Set a custom HTTP client to control timeout, proxy, TLS configuration, or other HTTP options. This example configures a custom transport with specific idle connection settings. ```go transport := &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableKeepAlives: false, } client := &youtube.Client{ HTTPClient: &http.Client{ Transport: transport, Timeout: 30 * time.Second, }, } video, _ := client.GetVideo("dQw4w9WgXcQ") ``` -------------------------------- ### List All Available Video Formats Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Video.md Retrieves a video and iterates through its available formats, printing details like quality label, MIME type, and resolution. ```go video, _ := client.GetVideo("dQw4w9WgXcQ") // List all available formats for i, format := range video.Formats { fmt.Printf("%d. Quality: %s, Type: %s, Resolution: %dx%d\n", i+1, format.QualityLabel, format.MimeType, format.Width, format.Height, ) } ``` -------------------------------- ### Android VR Client Configuration Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md Default client for Android VR. Works for most videos without requiring signature deciphering. ```go var AndroidVRClient = ClientInfo{ Name: "ANDROID_VR", Version: "1.65.10", Key: "", UserAgent: "com.google.android.apps.youtube.vr.oculus/1.65.10 (Linux; U; Android 12L; eureka-user Build/SQ3A.220605.009.A1) gzip", } ``` -------------------------------- ### Download First Video from Playlist Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Playlist.md Retrieves a playlist, extracts the first video entry, fetches its full metadata, and downloads it in the best available audio format. ```Go client := &youtube.Client{} playlist, _ := client.GetPlaylist("PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP") if len(playlist.Videos) == 0 { fmt.Println("Playlist is empty") return } firstEntry := playlist.Videos[0] fmt.Printf("Downloading: %s\n", firstEntry.Title) // Get full video metadata with all formats video, err := client.VideoFromPlaylistEntry(firstEntry) if err != nil { panic(err) } // Now video has all formats available formats := video.Formats.WithAudioChannels() formats.Sort() stream, _, err := client.GetStream(video, &formats[0]) if err != nil { panic(err) } defer stream.Close() file, _ := os.Create("video.mp4") defer file.Close() io.Copy(file, stream) fmt.Println("Download complete") ``` -------------------------------- ### Fetch and Display Transcript Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Transcript.md Demonstrates how to fetch a video's transcript in a specified language and display it. ```APIDOC ## Fetch and Display Transcript ### Description Fetches a video's transcript for a given language code and prints the full formatted transcript to the console. ### Usage ```go client := &youtube.Client{} video, err := client.GetVideo("dQw4w9WgXcQ") if err != nil { panic(err) } // Get English transcript transcript, err := client.GetTranscript(video, "en") if err != nil { panic(err) // Video may not have transcripts } // Display formatted transcript fmt.Println(transcript.String()) ``` ``` -------------------------------- ### High-Level Video Download with Progress Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Utilizes the downloader package for a simplified video download process, including output directory configuration and progress indication. Requires importing the downloader package. ```go import "github.com/kkdai/youtube/v2/downloader" dl := &downloader.Downloader{ OutputDir: "./videos", } video, _ := dl.GetVideo(videoID) formats := video.Formats.WithAudioChannels() formats.Sort() // Download with progress bar err := dl.Download(context.Background(), video, &formats[0], "") if err != nil { log.Fatalf("Download failed: %v", err) } ``` -------------------------------- ### List Available Transcript Languages Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Transcript.md Shows how to retrieve a video's caption tracks to list available transcript languages and their translatability. Also demonstrates fetching a transcript in a specific language (Spanish). ```go // Note: Language codes are returned by Video.CaptionTracks video, _ := client.GetVideo("dQw4w9WgXcQ") fmt.Println("Available transcripts:") for _, caption := range video.CaptionTracks { fmt.Printf(" %s (%s)\n", caption.Name.SimpleText, caption.LanguageCode) fmt.Printf(" Translatable: %v\n", caption.IsTranslatable) } // Get specific language transcript transcript, _ := client.GetTranscript(video, "es") // Spanish fmt.Println(transcript.String()) ``` -------------------------------- ### iOS Client Configuration Source: https://github.com/kkdai/youtube/blob/master/_autodocs/configuration.md iOS app client that functions similarly to the Android client. ```go var IOSClient = ClientInfo{ Name: "IOS", Version: "19.45.4", Key: "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8", UserAgent: "com.google.ios.youtube/19.45.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)", DeviceModel: "iPhone16,2", } ``` -------------------------------- ### Configure Client Source: https://github.com/kkdai/youtube/blob/master/_autodocs/INDEX.md Allows configuration of the YouTube client, including setting HTTP client timeouts, maximum concurrent routines for downloads, and chunk sizes for streaming. ```APIDOC ## Client Configuration ### Description Configures the `youtube.Client` for custom behavior like timeouts, download concurrency, and chunk size. ### Fields - **HTTPClient** (*http.Client): Custom HTTP client with configurable timeouts. - **MaxRoutines** (int): Maximum number of concurrent download routines. - **ChunkSize** (int64): Size of chunks for streaming downloads in bytes. ### Request Example ```go client := &youtube.Client{ HTTPClient: &http.Client{ Timeout: 30 * time.Second }, MaxRoutines: 20, ChunkSize: 50 * 1024 * 1024, // 50 MB chunks } // Or set log level youtube.SetLogLevel("debug") ``` ### Response No direct response, configuration is applied to the client instance. ``` -------------------------------- ### Enable Debug Logging for Testing Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Run your Go application with debug logging enabled by setting the LOGLEVEL environment variable. This helps in diagnosing issues during testing. ```bash export LOGLEVEL=debug go run myapp.go ``` -------------------------------- ### Client Struct Source: https://github.com/kkdai/youtube/blob/master/_autodocs/types.md The main API client for YouTube operations, holding HTTP client configuration and concurrency settings. ```go type Client struct { HTTPClient *http.Client MaxRoutines int ChunkSize int64 } ``` -------------------------------- ### Download YouTube Playlist Source: https://github.com/kkdai/youtube/blob/master/_autodocs/README.md Demonstrates how to download all videos from a YouTube playlist. It iterates through each video, selects the best audio-enabled format, and saves it as a numbered MP4 file. ```go client := &youtube.Client{} playlist, _ := client.GetPlaylist(playlistID) for i, entry := range playlist.Videos { video, err := client.VideoFromPlaylistEntry(entry) if err != nil { fmt.Printf("Skip %s: %v\n", entry.Title, err) continue } formats := video.Formats.WithAudioChannels() formats.Sort() filename := fmt.Sprintf("%03d.mp4", i+1) stream, _, _ := client.GetStream(video, &formats[0]) defer stream.Close() file, _ := os.Create(filename) io.Copy(file, stream) file.Close() fmt.Printf("Downloaded: %s\n", video.Title) } ``` -------------------------------- ### Filter and Download Specific Format from Playlist Source: https://github.com/kkdai/youtube/blob/master/_autodocs/api-reference/Playlist.md Iterates through a playlist, fetches each video's full metadata, filters for 720p quality with audio, and downloads the first matching format. ```Go client := &youtube.Client{} playlist, _ := client.GetPlaylist("PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP") for i, entry := range playlist.Videos { // Get full video video, err := client.VideoFromPlaylistEntry(entry) if err != nil { fmt.Printf("Error getting video %d: %v\n", i+1, err) continue } // Get 720p quality with audio formats := video.Formats.Quality("720p").WithAudioChannels() if len(formats) == 0 { fmt.Printf("%s: No 720p with audio\n", video.Title) continue } formats.Sort() stream, _, _ := client.GetStream(video, &formats[0]) defer stream.Close() filename := fmt.Sprintf("video_%d.mp4", i+1) file, _ := os.Create(filename) io.Copy(file, stream) file.Close() fmt.Printf("Downloaded: %s -> %s\n", video.Title, filename) } ```