Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
setattr(self, attr, val)
else:
# normal construction
try:
data = data if isinstance(data, (basestring, bytes)) else data.read()
except(OSError):
d = b''
reader = data.read(2 ** 31 - 1)
while reader:
d += reader
reader = data.read(2 ** 31 - 1)
data = d
wav_data = read_wav_audio(data)
if not wav_data:
raise CouldntDecodeError("Couldn't read wav audio from data")
self.channels = wav_data.channels
self.sample_width = wav_data.bits_per_sample // 8
self.frame_rate = wav_data.sample_rate
self.frame_width = self.channels * self.sample_width
self._data = wav_data.raw_data
# Convert 24-bit audio to 32-bit audio.
# (stdlib audioop and array modules do not support 24-bit data)
if self.sample_width == 3:
byte_buffer = BytesIO()
# Workaround for python 2 vs python 3. _data in 2.x are length-1 strings,
# And in 3.x are ints.
pack_fmt = 'BBB' if isinstance(self._data[0], int) else 'ccc'
tango.tstart = 0
tango.tend = 0
tango.duration = len(song)
data.updateTango(tango)
except FileNotFoundError:
print (start+"We can not find the file of "+str(tango.ID));
backspace(sizeBackSpace)
print(toPrint)
except KeyboardInterrupt:
backspace(sizeBackSpace)
print(toPrint)
print(start+"KeyboardInterrupt")
exit(0)
except pydub.exceptions.CouldntDecodeError as e:
clear()
backspace(sizeBackSpace)
print(toPrint)
print(start+"Can't Decode "+str(tango.ID)+" "+tango.path)
pass
.. warning:: This method uses the program 'sox' to perform the task. While this is very fast for a single
function call, the IO may add up for large numbers of AudioSegment objects.
:param duration_s: The number of seconds of "silence" that must be present in a row to
be stripped.
:param threshold_percentage: Silence is defined as any samples whose absolute value is below
`threshold_percentage * max(abs(samples in this segment))`.
:param console_output: If True, will pipe all sox output to the console.
:returns: A copy of this AudioSegment, but whose silence has been removed.
"""
command = "sox {inputfile} -t wav {outputfile} silence -l 1 0.1 "\
+ str(threshold_percentage) + "% -1 " + str(float(duration_s)) + " " + str(threshold_percentage) + "%"
try:
result = self._execute_sox_cmd(command)
except pydub.exceptions.CouldntDecodeError:
warnings.warn("After silence filtering, the resultant WAV file is corrupted, and so its data cannot be retrieved. Perhaps try a smaller threshold value.", stacklevel=2)
# Return a copy of us
result = AudioSegment(self.seg, self.name)
return result
def process(self):
"""Normalize &c. the audio file, if possible
When we have an audio processor, process the file
(i.e. normalize, remove silence, convert to preferred format)
and update self.
"""
if processor:
try:
new_fp, new_sffx = processor.process(self)
except pydub.exceptions.CouldntDecodeError:
self.action = Action.Delete
else:
self.file_path = new_fp
self.file_extension = new_sffx
if not fmt or fmt[0].size < 16:
raise CouldntDecodeError("Couldn't find fmt header in wav data")
fmt = fmt[0]
pos = fmt.position + 8
audio_format = struct.unpack_from('
"-"
]
if parameters is not None:
# extend arguments with arbitrary set
conversion_command.extend(parameters)
log_conversion(conversion_command)
p = subprocess.Popen(conversion_command, stdin=stdin_parameter,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p_out, p_err = p.communicate(input=stdin_data)
if p.returncode != 0 or len(p_out) == 0:
file.close()
raise CouldntDecodeError(
"Decoding failed. ffmpeg returned error code: {0}\n\nOutput from ffmpeg/avlib:\n\n{1}".format(
p.returncode, p_err))
p_out = bytearray(p_out)
fix_wav_headers(p_out)
obj = cls._from_safe_wav(BytesIO(p_out))
file.close()
return obj
keep_silence (int): Amound of start/end silence to keep (in ms).
Returns:
list: The output file names.
"""
def _export_segments(segments):
fnames = []
for i, seg in enumerate(segments):
fname = '{}_{}.wav'.format(os.path.splitext(file_name)[0], i)
seg.export(os.path.join(output_path, fname), format='wav')
fnames.append(fname)
return fnames
try:
x = AudioSegment.from_wav(os.path.join(dataset_path, file_name))
except CouldntDecodeError:
x = AudioSegment.empty()
# Skip audio clips that are not longer than the padding
# Padding refers to the silence that is kept for each segment
padding = keep_silence * 2
if x.duration_seconds <= padding / 1000:
return _export_segments([x])
# Determine silence threshold based on whether the audio signal
# consists entirely of transients.
if _is_transients(x.get_array_of_samples(), x.frame_rate, n_window):
threshold = transients_threshold
else:
threshold = default_threshold
segments = silence.split_on_silence(
def read_wav_audio(data, headers=None):
if not headers:
headers = extract_wav_headers(data)
fmt = [x for x in headers if x.id == b'fmt ']
if not fmt or fmt[0].size < 16:
raise CouldntDecodeError("Couldn't find fmt header in wav data")
fmt = fmt[0]
pos = fmt.position + 8
audio_format = struct.unpack_from('
def read_wav_audio(data, headers=None):
if not headers:
headers = extract_wav_headers(data)
fmt = [x for x in headers if x.id == b'fmt ']
if not fmt or fmt[0].size < 16:
raise CouldntDecodeError("Couldn't find fmt header in wav data")
fmt = fmt[0]
pos = fmt.position + 8
audio_format = struct.unpack_from('
if parameters is not None:
# extend arguments with arbitrary set
conversion_command.extend(parameters)
log_conversion(conversion_command)
with open(os.devnull, 'rb') as devnull:
p = subprocess.Popen(conversion_command, stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p_out, p_err = p.communicate()
log_subprocess_output(p_out)
log_subprocess_output(p_err)
try:
if p.returncode != 0:
raise CouldntDecodeError(
"Decoding failed. ffmpeg returned error code: {0}\n\nOutput from ffmpeg/avlib:\n\n{1}".format(
p.returncode, p_err))
obj = cls._from_safe_wav(output)
finally:
input_file.close()
output.close()
os.unlink(input_file.name)
os.unlink(output.name)
return obj