Friday, November 25, 2022

Konversi Fail Stereo ke Mono Dari Direktori Berisi Banyak Fail Suara

Skrip berikut dapat merubah fail suara stereo ke mono dari suatu direktori (termasuk subdirektori di dalamnya) yang diberikan.
Input: Direktori/folder
Output: Fail berakhiran "_mono" dengan direktori yang sama terhadap input (termasuk subdirektori)
#!/usr/bin/env python3
import os
import argparse
import glob
from pydub import AudioSegment

def stereo2mono(files):
    """Convert all files from stereo to mono.
    Note: this would effectively also create a copy of files that were already in a mono format
    Parameters
    ----------
    files : iterable
        Sequence of files
    Example use:
    ```
    $ python3 stereo2mono.py -f /path/to/audio/files/
    ```
    Then you may remove the files that do not contain the '_mono' tag with: 
    $ find . -name "*-??.wav" -delete # for emovo
    """
    for f in files:
        print(f"Converting {f}")
        # Load audio
        sound = AudioSegment.from_wav(f)
        # Convert to mono
        sound = sound.set_channels(1)
        # Save file
        stem, ext = os.path.splitext(f)
        sound.export(f'{stem}_mono{ext}', format='wav')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Convert stereo to mono')
    parser.add_argument('-f', '--folder', 
        type=str, help='Path to wavfiles')
    args = parser.parse_args()
    files = glob.glob(args.folder + '**/*.wav', recursive=True)
    stereo2mono(files)
Contoh penggunaan
# Konversi ke mono
python3 stereo2mono.py -f tensorflow_datasets/downloads/extracted/ZIP.emovo.zip/EMOVO/
# menghapus file yang bukan mono
$ pwd
/home/bagus/tensorflow_datasets/downloads/extracted/ZIP.emovo.zip/EMOVO/
$ find . -name "*-??.wav" -delete
Referensi gist:
1. https://gist.github.com/bagustris/40b406d99820207bc804a020db169f7e
Related Posts Plugin for WordPress, Blogger...