#lang racket/base (require racket/file racket/path "util.rkt") (provide convert-flac-to-target-in-place) (define (temp-output-path input-path) (define-values (base name dir?) (split-path input-path)) (define name-str (path->string name)) (build-path base (format ".~a.tmp-~a.flac" name-str (current-inexact-milliseconds)))) (define (delete-file/quiet! p) (with-handlers ([exn:fail? (lambda (_) (void))]) (when (file-exists? p) (delete-file p)))) (define (settings max-sample-rate compression-level) (make-immutable-hash (list (cons 'target-sample-rate max-sample-rate) (cons 'compression-level compression-level)))) (define (call-audio-encode audio-encode in-file out-file settings progress-callback) (if progress-callback (audio-encode in-file out-file settings #:encoder 'flac #:copy-tags? #t #:progress-callback progress-callback) (audio-encode in-file out-file settings #:encoder 'flac #:copy-tags? #t))) (define (convert-flac-to-target-in-place input-path max-sample-rate compression-level #:progress-callback [progress-callback #f]) (define tmp-path (temp-output-path input-path)) (with-handlers ([exn:break? (lambda (e) (delete-file/quiet! tmp-path) (raise e))] [exn:fail? (lambda (e) (delete-file/quiet! tmp-path) (raise e))]) (define audio-encode (dynamic-require 'racket-audio/audio-encoder 'audio-encode)) (define result (call-audio-encode audio-encode input-path tmp-path (settings max-sample-rate compression-level) progress-callback)) (rename-file-or-directory tmp-path input-path #t) result))