Skip to content

Instantly share code, notes, and snippets.

@etowett
Created March 21, 2018 04:32
Show Gist options
  • Save etowett/82a8880c41d2631b04a7b9a6c9b05948 to your computer and use it in GitHub Desktop.
Save etowett/82a8880c41d2631b04a7b9a6c9b05948 to your computer and use it in GitHub Desktop.
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
)
func main() {
givenArg := flag.String("a", "", "File|Directory to be converted")
toDel := flag.Bool("d", false, "To delete the file?")
flag.Parse()
if *givenArg == "" {
flag.PrintDefaults()
os.Exit(1)
}
if _, err := os.Stat(*givenArg); os.IsNotExist(err) {
fmt.Printf("ERROR: given file (%s) does not exist\n", *givenArg)
os.Exit(1)
}
err := convert(*givenArg, *toDel)
if err != nil {
fmt.Printf("ERROR: Convert failed: %v\n", err)
os.Exit(1)
}
fmt.Println("Conversion done")
return
}
func convert(givenArg string, toDel bool) error {
isDir, err := isDirectory(givenArg)
if err != nil {
return fmt.Errorf("is directory error: %v", err)
}
if isDir {
files, err := ioutil.ReadDir(givenArg)
if err != nil {
return fmt.Errorf("couldn't read dir: %v", err)
}
for _, file := range files {
if givenArg[len(givenArg)-1:] != "/" {
givenArg = givenArg + "/"
}
err := workon(givenArg+file.Name(), toDel)
if err != nil {
return fmt.Errorf("workon: %v", err)
}
}
} else {
err := workon(givenArg, toDel)
if err != nil {
return fmt.Errorf("workon: %v", err)
}
}
return nil
}
func isDirectory(path string) (bool, error) {
fileInfo, err := os.Stat(path)
return fileInfo.IsDir(), err
}
func workon(given string, del bool) error {
var allowedExts = []string{"mp4", "mkv", "flv", "avi"}
var sl = strings.Split(given, ".")
var ext = sl[len(sl)-1]
var finalName = strings.Join(sl[:len(sl)-1], ".") + ".mp3"
if _, err := os.Stat(finalName); !os.IsNotExist(err) {
fmt.Printf("EXISTS: %s\n", finalName)
if del {
err := remove(given)
if err != nil {
return fmt.Errorf("remove error: %s", given)
}
}
} else if inSlice(strings.ToLower(ext), allowedExts) {
fmt.Printf("CONVERT: %s\n", given)
cmd := fmt.Sprintf("ffmpeg -i '%s' -vn -ar 44100 -ac 2 -ab 192k -f mp3 '%s'", given, finalName)
output, err := exec.Command(cmd).CombinedOutput()
if err != nil {
// os.Stderr.WriteString(err.Error())
return fmt.Errorf("exec error: %v", err)
}
fmt.Println(string(output))
} else {
return fmt.Errorf("extension unknown: %v", err)
}
return nil
}
func remove(path string) error {
err := os.Remove(path)
if err != nil {
return fmt.Errorf("os remove: %v", err)
}
return nil
}
func inSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func shellQuote(file string) string {
var replacer = strings.NewReplacer(
` `, `\ `, `(`, `\(`, `)`, `\)`, `&`, `\&`,
)
return replacer.Replace(file)
// return "'" + replacer.Replace(file) + "'"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment