# HG changeset patch # User Amine Sehili # Date 1547306387 -3600 # Node ID 4dcbc6ae39c7111a3104cf5b4baa3a2057440365 # Parent 0335e53c8391e494c9113d7aa91cf478e93486b1 Add _save_with_pydub diff -r 0335e53c8391 -r 4dcbc6ae39c7 auditok/io.py --- a/auditok/io.py Fri Jan 11 20:55:42 2019 +0100 +++ b/auditok/io.py Sat Jan 12 16:19:47 2019 +0100 @@ -29,6 +29,12 @@ import sys import wave +try: + from pydub import AudioSegment + _WITH_PYDUB = True +except ImportError: + _WITH_PYDUB = False + __all__ = ["AudioIOError", "AudioParameterError", "AudioSource", "Rewindable", "BufferAudioSource", "WaveAudioSource", "PyAudioSource", "StdinAudioSource", "PyAudioPlayer", "from_file", "player_for"] @@ -542,26 +548,6 @@ start += chunk_size -def _save_raw(filename, data): - """ - Save audio data as a headerless (i.e. raw) file. - """ - with open(filename, "wb") as fp: - fp.write(data) - - -def _save_wave(filename, data, sampling_rate, sample_width, channels): - """ - Save audio data to a wave file. - """ - # use standard python's wave module - with wave.open(filename, "w") as fp: - fp.setframerate(sampling_rate) - fp.setsampwidth(sample_width) - fp.setnchannels(channels) - fp.writeframes(data) - - def from_file(filename): """ Create an `AudioSource` object using the audio file specified by `filename`. @@ -602,6 +588,42 @@ audio_source.get_sample_width(), audio_source.get_channels()) +def _save_raw(file, data): + """ + Saves audio data as a headerless (i.e. raw) file. + See also :func:`to_file`. + """ + with open(file, "wb") as fp: + fp.write(data) + + +def _save_wave(file, data, sampling_rate, sample_width, channels): + """ + Saves audio data to a wave file. + See also :func:`to_file`. + """ + # use standard python's wave module + with wave.open(file, "w") as fp: + fp.setframerate(sampling_rate) + fp.setsampwidth(sample_width) + fp.setnchannels(channels) + fp.writeframes(data) + + +def _save_with_pydub(file, data, audio_format, sampling_rate, sample_width, + channels): + """ + Saves audio data with pydub (https://github.com/jiaaro/pydub). + See also :func:`to_file`. + """ + segment = AudioSegment(data, + frame_rate=sampling_rate, + sample_width=sample_width, + channels=channels) + with open(file, "wb") as fp: + segment.export(fp, format=audio_format) + + def to_file(data, file, audio_format=None, **kwargs): """ Writes audio data to file. If `audio_format` is `None`, output