-
Notifications
You must be signed in to change notification settings - Fork 448
/
example_test.go
89 lines (70 loc) · 1.73 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package youtube_test
import (
"fmt"
"io"
"os"
"strings"
"github.com/kkdai/youtube/v2"
)
// ExampleDownload : Example code for how to use this package for download video.
func ExampleClient() {
videoID := "BaW_jenozKc"
client := youtube.Client{}
video, err := client.GetVideo(videoID)
if err != nil {
panic(err)
}
formats := video.Formats.WithAudioChannels() // only get videos with audio
stream, _, err := client.GetStream(video, &formats[0])
if err != nil {
panic(err)
}
defer stream.Close()
file, err := os.Create("video.mp4")
if err != nil {
panic(err)
}
defer file.Close()
_, err = io.Copy(file, stream)
if err != nil {
panic(err)
}
}
// Example usage for playlists: downloading and checking information.
func ExamplePlaylist() {
playlistID := "PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP"
client := youtube.Client{}
playlist, err := client.GetPlaylist(playlistID)
if err != nil {
panic(err)
}
/* ----- Enumerating playlist videos ----- */
header := fmt.Sprintf("Playlist %s by %s", playlist.Title, playlist.Author)
println(header)
println(strings.Repeat("=", len(header)) + "\n")
for k, v := range playlist.Videos {
fmt.Printf("(%d) %s - '%s'\n", k+1, v.Author, v.Title)
}
/* ----- Downloading the 1st video ----- */
entry := playlist.Videos[0]
video, err := client.VideoFromPlaylistEntry(entry)
if err != nil {
panic(err)
}
// Now it's fully loaded.
fmt.Printf("Downloading %s by '%s'!\n", video.Title, video.Author)
stream, _, err := client.GetStream(video, &video.Formats[0])
if err != nil {
panic(err)
}
file, err := os.Create("video.mp4")
if err != nil {
panic(err)
}
defer file.Close()
_, err = io.Copy(file, stream)
if err != nil {
panic(err)
}
println("Downloaded /video.mp4")
}