Last active
December 5, 2022 03:12
-
-
Save hellojukay/6ff2fb1721898f1627ea674c8821a69c to your computer and use it in GitHub Desktop.
转化 wma 格式音频文件为 mp3 格式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"log" | |
"os" | |
"os/exec" | |
"path/filepath" | |
"strings" | |
"sync" | |
) | |
var ( | |
dir string | |
thread int | |
delete bool | |
) | |
func init() { | |
flag.StringVar(&dir, "dir", "./", "Input directory") | |
flag.IntVar(&thread, "t", 1, "The number of threads") | |
flag.BoolVar(&delete, "delete", false, "Delete the old format file") | |
flag.Parse() | |
} | |
func listFiles(dir string) []string { | |
var result []string | |
err := filepath.Walk(dir, | |
func(path string, info os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
result = append(result, path) | |
return nil | |
}) | |
if err != nil { | |
log.Println(err) | |
} | |
return result | |
} | |
func tomp3(file string) error { | |
newFile := strings.Replace(file, ".wma", ".mp3", -1) | |
cmd := exec.Command("/usr/bin/ffmpeg", "-y", "-i", file, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "192k", newFile) | |
cmd.Stdout = os.Stdout | |
cmd.Stderr = os.Stderr | |
return cmd.Run() | |
} | |
func work(c chan string) { | |
for file := range c { | |
if err := tomp3(file); err != nil { | |
println(file, "... error", err.Error()) | |
} else { | |
println(file, "... finished") | |
if delete { | |
os.Remove(file) | |
} | |
} | |
} | |
} | |
func main() { | |
var wg sync.WaitGroup | |
var c chan string = make(chan string, 1) | |
var files = listFiles(dir) | |
for i := 0; i < thread; i++ { | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
work(c) | |
}() | |
} | |
for _, file := range files { | |
if strings.HasSuffix(file, ".wma") { | |
c <- file | |
continue | |
} | |
println(file, "skipped") | |
} | |
close(c) | |
wg.Wait() | |
println("all finished") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment