Skip to content

Instantly share code, notes, and snippets.

@etowett
Last active November 16, 2017 09:35
Show Gist options
  • Save etowett/eb16d470d285a07b644b98de5eee7676 to your computer and use it in GitHub Desktop.
Save etowett/eb16d470d285a07b644b98de5eee7676 to your computer and use it in GitHub Desktop.
Convert video files (single or in a folder) to mp3
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) + "'"
}
#!/usr/bin/env python2.7
import os
import sys
import argparse
def shellquote(s):
s = s.replace("'", "\\'")
s = s.replace(" ", "\ ")
s = s.replace("(", "\(")
s = s.replace(")", "\)")
s = s.replace("&", "\&")
return "'" + s + "'"
def remove(filn):
filn = filn
print "DELETE: %s" % (filn)
if os.path.exists(filn):
print os.remove(filn)
return
def convert(arg, delete):
allowed_exts = ['mp4', 'mkv', 'flv', 'avi']
ext = arg.split('.')[-1]
final = '.'.join(arg.split('.')[:-1]) + '.mp3'
if os.path.exists(final):
print "EXISTS: %s" % final
if delete:
remove(arg)
return
if ext.lower() in allowed_exts:
print "CONVERT: %s" % shellquote(arg)
print os.system(
"ffmpeg -i '%s' -vn -ar 44100 -ac 2 -ab 192k -f mp3 '%s'" %
(shellquote(arg), shellquote(final),)
)
if delete:
remove(arg)
else:
print "NOT_SUPPORTED: %s" % arg
return
def main(arg, delete):
if os.path.isfile(arg):
convert(arg, delete)
elif os.path.isdir(arg):
for filename in os.listdir(arg):
if arg[-1] != '/':
arg = arg + '/'
convert(arg + filename, delete)
else:
print >>sys.stderr, 'ERROR: given argument not supported\n%s' % arg
sys.exit(1)
return
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Convert video to mp3")
parser.add_argument('arg', help='File|Directory to be converted')
parser.add_argument(
"-d", "--delete", action="store_true", help="To delete the file?"
)
args = parser.parse_args()
if not os.path.exists(args.arg):
print >>sys.stderr, 'ERROR: given file does not exist'
sys.exit(1)
main(args.arg, args.delete)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment