kkdai / youtube

Download Youtube Video in Golang
MIT License
3.3k stars 430 forks source link

How to download 1080p video with audio inside a golang program? #330

Open ruizlenato opened 4 months ago

ruizlenato commented 4 months ago

image

Is there any way I can do this within my golang program? I want to download a video in 1080p + audio, I couldn't find anything in the references

Yuelioi commented 2 months ago

Some function maybe you can use


// FilterFormats filters a list of YouTube formats based on a specific kind (e.g. "video/mp4")
func FilterFormats(formats youtube.FormatList, kind string) []youtube.Format {
    var filteredFormats []youtube.Format
    for _, format := range formats {
        if strings.Contains(format.MimeType, kind) {
            filteredFormats = append(filteredFormats, format)
        }
    }
    return filteredFormats
}

// GetBestHighFormat returns the format with the highest bitrate from a list of formats
func GetBestHighFormat(formats []youtube.Format) youtube.Format {
    var bestFormat youtube.Format
    for _, format := range formats {
        if format.Bitrate > bestFormat.Bitrate {
            bestFormat = format
        }
    }
    return bestFormat
}

func GetVideoDataById(videoID string) (*youtube.Client, *youtube.Video) {
    client := GetClient()

    if client == nil {
        panic("Cannot connect client")
    }

    video, err := client.GetVideo(videoID)
    if err != nil {
        panic(err)
    }
    return client, video
}

func DownloadVideoOrAudioByVideoData(client *youtube.Client, video *youtube.Video, folder string, index int) {
    title := utils.SanitizeFileName(video.Title)

    if index != 0 {
        title = strconv.Itoa(index) + "_" + title
    }

    formats_highest_v := GetBestHighFormat(FilterFormats(video.Formats, "video"))
    formats_highest_a := GetBestHighFormat(FilterFormats(video.Formats, "audio"))

    DownloadStream(client, video, &formats_highest_v, folder+"/"+title+".mp4")
    DownloadStream(client, video, &formats_highest_a, folder+"/"+title+".flc")
}

func DownloadStream(client *youtube.Client, video *youtube.Video, format *youtube.Format, filepath string) {
    stream, _, err := client.GetStream(video, format)
    if err != nil {
        panic(err)
    }
    defer stream.Close()

    file, err := os.Create(filepath)
    if err != nil {
        panic(err)
    }
    defer file.Close()

    _, err = io.Copy(file, stream)
    if err != nil {
        panic(err)
    }
}
peterjumper commented 2 months ago

it has build-in function, use it:

youtubedr download -m mp4 -q hd720 "$(pbpaste)"

if u want to use webm for higher quality, you can use ffmpeg -i input.webm -i input.m4a -c copy -map 0:v:0 -map 1:a:0 output.mp4

this would the fastest way to convert (from my poor experience), but u have to manually pick audio and video first

kiroInn commented 1 week ago

@peterjumper it works for me, thanks