Skip to content

Instantly share code, notes, and snippets.

@fosskers
Last active February 10, 2023 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fosskers/76a9770c2bdcf66126b0a1614f33729e to your computer and use it in GitHub Desktop.
Save fosskers/76a9770c2bdcf66126b0a1614f33729e to your computer and use it in GitHub Desktop.
Emacs Lisp: Extract all the audio from a file or directory of files
(defun extract-audio (choice)
"Extract the audio from a chosen file or directory of files."
(interactive "fVideo File or Directory: ")
(cond ((file-directory-p choice)
(thread-last (directory-files choice 'full)
(seq-filter (lambda (file) (not (file-directory-p file))))
(mapc #'extract-audio-from-file))
(message "Done converting: %s" choice))
(t (extract-audio-from-file choice))))
(defun extract-audio-from-file (file)
"Extract the audio from a given video FILE."
(let* ((file (expand-file-name file))
(audio (audio-format file))
(target (file-name-with-extension file audio))
(result (doom-call-process "ffmpeg" "-i" file "-vn" "-acodec" "copy" target)))
(pcase result
(`(1 . ,_) (error "Failed to convert: %s" file))
(`(0 . ,_) (message "Converted: %s" target)))))
(defun audio-format (file)
"What is the audio format of the given video FILE?"
(let ((result (doom-call-process "ffprobe" file)))
(pcase result
(`(1 . ,_) (error "%s is not a video file." file))
(`(0 . ,out)
(string-match "Audio: \\([a-z]+\\)," out)
(match-string 1 out)))))
@fosskers
Copy link
Author

Note: this requires at least Emacs 28.1 to use file-name-with-extension. Usage of Doom Emacs is also necessary if you want to use doom-call-process, which is a very convenient wrapper around calling shell processes.

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