现在还不知道如何爬取视频地址,用插件获取视频地址
在项目里新建1.txt,粘贴进去
go代码部分合并了上面的带进度条下载和执行cmd命令部分
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strconv"
)
type WriteCounter struct {
Total uint64
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Total += uint64(n)
wc.PrintProgress()
return n, nil
}
func (wc WriteCounter) PrintProgress() {
fmt.Printf("\rDownloading... %d complete", wc.Total)
}
func main() {
s := readfile("./1.txt")
var filename string
for i, u := range s {
filename = strconv.Itoa(i) + ".ts" //int转成string
writefile("file '" + filename + "'\n")
DownloadFile(filename, u)
}
fmt.Printf("download completed!")
runcmd()
delfile()
}
func DownloadFile(filepath string, url string) error {
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Create our progress reporter and pass it to be used alongside our writer
counter := &WriteCounter{}
_, err = io.Copy(out, io.TeeReader(resp.Body, counter))
if err != nil {
return err
}
// The progress use the same line so print a new line once it's finished downloading
fmt.Print("\n")
return nil
}
func readfile(path string) []string {
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
br := bufio.NewReader(file)
s := make([]string, 0)
for {
a, _, c := br.ReadLine() //按行读取
if c == io.EOF {
break
}
s = append(s, string(a)) //追加到切片
}
return s
}
func writefile(f string) { //创建list.txt文件再写入
filePath := "list.txt"
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Println("open file err", err)
}
//及时关闭file句柄
defer file.Close()
//写入文件时,使用带缓存的 *Writer
write := bufio.NewWriter(file)
write.WriteString(f)
//Flush将缓存的文件真正写入到文件中
write.Flush()
}
func runcmd() {
cmd := exec.Command("cmd.exe", "/c", `C:\ffmpeg\ffmpeg.exe -f concat -safe 0 -i list.txt -c copy output.mp4`)
err := cmd.Run()//start不等返回就接着执行下面的代码,Run会等待命令执行完在执行后面的
if err != nil {
log.Fatal(err)
}
}
func delfile() {//删除文件
var s string
files, _ := ioutil.ReadDir("./")
for _, f := range files {
s = f.Name()
if s[2:] == "ts" {
os.Remove(f.Name()) //删除文件
}
}
}