ts格式转MP4格式
大约 1 分钟
package main
import (
"flag"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
var (
outPath = "mp4"
failPath = "fail"
fileList []string
basePath = ""
worker = 1
number = "1"
)
func checkFfmpg() bool {
cmd := exec.Command("ffmpeg", "-version")
err := cmd.Run()
if err != nil {
return false
}
return true
}
func mkDir(dirname string) {
_, err := os.Stat(dirname)
if err != nil {
err = os.Mkdir(dirname, 0777)
if err != nil {
panic("文件夹创建失败" + err.Error())
}
}
}
func init() {
if ok := checkFfmpg(); !ok {
log.Print("ffmpg未安装,随便找个ai问一下如何安装即可")
log.Print("ffmpeg官网:https://www.ffmpeg.org")
return
}
flag.StringVar(&basePath, "d", "", "请输入需要转化的目录,默认为当前目录")
flag.StringVar(&number, "c", number, "同时处理任务数")
flag.Parse()
if basePath != "" {
info, err := os.Stat(basePath)
if err != nil {
log.Print(err)
return
}
if !info.IsDir() {
log.Print(basePath + ":不是一个目录")
return
}
} else {
getwd, err2 := os.Getwd()
if err2 != nil {
log.Print(err2)
return
}
basePath = getwd
}
n, _ := strconv.Atoi(number)
if n > 1 {
worker = n
}
mkDir(filepath.Join(basePath, outPath))
mkDir(filepath.Join(basePath, failPath))
// 读取当前目录下的文件列表
list, err3 := os.ReadDir(basePath)
if err3 != nil {
log.Print(err3)
return
}
for _, file := range list {
if !file.IsDir() && strings.HasSuffix(file.Name(), "mp4") {
fileList = append(fileList, file.Name())
}
}
if len(fileList) == 0 {
log.Print("当前目录目录没有可转换的文件")
return
}
}
func toMp4(basePath, inputName, outPath string, ch chan int) {
inputPath := filepath.Join(basePath, inputName)
outputPath := filepath.Join(basePath, outPath, inputName)
cmd := exec.Command("ffmpeg", "-i", inputPath, "-c:v", "copy", "-c:a", "copy", outputPath)
err := cmd.Run()
if err != nil {
ch <- 0
log.Print("转换失败:", inputName)
return
}
err = os.Remove(inputPath)
if err != nil {
ch <- 0
return
}
log.Printf("%s -> ok", inputName)
ch <- 1
}
/*
*
将当前目录下载的ts文件转换为mp4文件
命令: ffmpeg -i 1.ts -c:v copy -c:a copy output.mp4
用法 ts2mp4 -h
*/
func main() {
log.Print("执行目录:", basePath)
log.Print("转化成功目录:", filepath.Join(basePath, outPath))
log.Print("转化失败目录:", filepath.Join(basePath, failPath))
log.Print("同时处理任务数:", worker)
log.Print("累计转化文件:", len(fileList))
ch := make(chan int, worker)
for _, name := range fileList {
go toMp4(basePath, name, outPath, ch)
}
for i := 0; i < len(fileList); i++ {
<-ch
}
log.Print("转换完成,累计转化:", len(fileList))
}