Skip to content

Instantly share code, notes, and snippets.

@navopw
Last active August 25, 2022 22:06
Show Gist options
  • Save navopw/a27d57d8dbc34e7129ed8c38ceea94d0 to your computer and use it in GitHub Desktop.
Save navopw/a27d57d8dbc34e7129ed8c38ceea94d0 to your computer and use it in GitHub Desktop.
Convert .mov to .mp4 recursively in folder (Go)
package main
import (
"fmt"
ffmpeg "github.com/u2takey/ffmpeg-go"
"log"
"os"
"path/filepath"
"strings"
)
func main() {
path := "YOUR DIRECTORY PATH :-)"
wDir, _ := os.Getwd()
outputFolder := wDir + "/output"
os.Mkdir(outputFolder, 0755)
var movFiles []string
// Find .mov files
err := filepath.Walk(path, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// If file is a .mov file
if filepath.Ext(filePath) == ".mov" {
movFiles = append(movFiles, filePath)
}
return nil
})
if err != nil {
log.Println(err)
}
// Convert .mov files to .mp4
for _, movFile := range movFiles {
// Output path
fileName := FileNameWithoutExt(filepath.Base(movFile))
outputPath := outputFolder + "/" + fileName + ".mp4"
// ffmpeg
println("Converting " + movFile)
args := ffmpeg.KwArgs{
"c:v": "libx265",
"preset": "medium",
}
ffmpegError := ffmpeg.Input(movFile).Output(outputPath, args).ErrorToStdOut().Run()
if ffmpegError != nil {
panic(ffmpegError)
}
// Size before
sizeBefore := GetFileSize(movFile)
sizeAfter := GetFileSize(outputPath)
// Print size
println("Size before: " + GetFileSizeInHumanFormat(sizeBefore))
println("Size after: " + GetFileSizeInHumanFormat(sizeAfter))
}
}
func GetFileSizeInHumanFormat(fileSize int64) string {
if fileSize < 1024 {
return fmt.Sprintf("%d B", fileSize)
}
if fileSize < 1024*1024 {
return fmt.Sprintf("%d KB", fileSize/1024)
}
if fileSize < 1024*1024*1024 {
return fmt.Sprintf("%d MB", fileSize/1024/1024)
}
return fmt.Sprintf("%d GB", fileSize/1024/1024/1024)
}
func GetFileSize(filePath string) int64 {
file, err := os.Open(filePath)
if err != nil {
log.Fatal(err)
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Fatal(err)
}
}(file)
fileInfo, fileInfoError := file.Stat()
if fileInfoError != nil {
log.Fatal(fileInfoError)
}
return fileInfo.Size()
}
func FileNameWithoutExt(fileName string) string {
return strings.TrimSuffix(fileName, filepath.Ext(fileName))
}
@navopw
Copy link
Author

navopw commented Aug 25, 2022

You need to have ffmpeg installed.

For Mac users with Homebrew: brew install ffmpeg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment