Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
jiaaro authored Feb 3, 2017
2 parents 6b585b8 + 917677d commit 99d910c
Show file tree
Hide file tree
Showing 10 changed files with 253 additions and 26 deletions.
25 changes: 25 additions & 0 deletions API.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,33 @@ from pydub import AudioSegment
sound = AudioSegment.from_file(“sound1.wav”)

samples = sound.get_array_of_samples()

# then modify samples...

new_sound = sound._spawn(samples)
```

### AudioSegment(…).get_dc_offset()

Returns a value between -1.0 and 1.0 representing the DC offset of a channel. This is calculated using `audioop.avg()` and normalizing the result by samples max value.

**Supported keyword arguments**:

- `channel` | example: `2` | default: `1`
Selects left (1) or right (2) channel to calculate DC offset. If segment is mono, this value is ignored.

### AudioSegment(…).remove_dc_offset()

Removes DC offset from channel(s). This is done by using `audioop.bias()`, so watch out for overflows.

**Supported keyword arguments**:

- `channel` | example: `2` | default: None
Selects left (1) or right (2) channel remove DC offset. If value if None, removes from all available channels. If segment is mono, this value is ignored.

- `offset` | example: `-0.1` | default: None
Offset to be removed from channel(s). Calculates offset if it's None. Offset values must be between -1.0 and 1.0.

## Effects

Collection of DSP effects that are implemented by `AudioSegment` objects.
Expand Down
3 changes: 3 additions & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,6 @@ André Cloete

David Acacio
github: dacacioa

Thiago Abdnur
github: bolaum
88 changes: 88 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# v0.16.7
- Make `pydub.AudioSegment()._spawn()` accept array.array instances containing audio samples

# v0.16.6
- Make `pydub.AudioSegment()` objects playable inline in ipython notebooks.
- Add scipy powered high pass, low pass, and band pass filters, which can be high order filters (they take `order` as a keyword argument). They are used for `pydub.AudioSegment().high_pass_filter()`, `pydub.AudioSegment().low_pass_filter()`, `pydub.AudioSegment().band_pass_filter()` when the `pydub.scipy_effects` module is imported.
- Fix minor bug in `pydub.silence.detect_silence()`

# v0.16.5
- Update `pydub.AudioSegment()._spawn()` method to allow user subclassing of `pydub.AudioSegment`
- Add a workaround for incorrect duration reporting of some mp3 files on macOS

# v0.16.4
- Add support for radd (basically, allow `sum()` to operate on an iterable of `pydub.AudioSegment()` objects)
- Fix bug in 24-bit wav support (understatement. It didn't work right at all the first time)

# v0.16.3
- Add support for python 3.5 (overstatement. We just added python 3.5 to CI and it worked 😄)
- Add native support for 24-bit wav files (ffmpeg/avconv not required)

# v0.16.2
- Fix bug where you couldn't directly instantiate `pydub.AudioSegment` with `bytes` data in python 3

# v0.16.1
- pydub will use any ffmpeg/avconv binary that's in the current directory (as reported by `os.getcwd()`) before searching for a system install

# v0.16.0
- Add `pydub.AudioSegment.from_data()` constructor for creating audio segments from raw audio data (without having to write it to a file first)
- Add `pydub.AudioSegment().get_array_of_samples()` method which returns the samples which make up an audio segment (you should usually prefer this over `pydub.AudioSegment().raw_data`)
- Add `pydub.AudioSegment().raw_data` property which returns the raw audio data for an audio segment as a bytes (python 3) or a bytestring (python 3)
- Allow users to specify frame rate in `pydub.AudioSegment.silent()` constructor

# v0.15.0
- Add support for RAW audio (basically WAV format, but without wave headers)
- Add a new exception `pydub.exceptions.CouldntDecodeError` to indicate a failure of ffmpeg/avconv to decode a file (as indicated by ffmpeg/avconv exit code)

# v0.14.2
- Fix a bug in python 3.4 which failed to read wave files with no audio data (should have been audio segments with a duration of 0 ms)

# v0.14.1
- Fix a bug in `pydub.utils.mediainfo()` that caused inputs containing unescaped characters to raise a runtime error (inputs are not supposed to require escaping)

# v0.14.0
- Rename `pydub.AudioSegment().set_gain()` to `pydub.AudioSegment().apply_gain_stereo()` to better reflect it's place in the world (as a counterpart to `pydub.AudioSegment().apply_gain()`)

# v0.13.0
- Add `pydub.AudioSegment().pan()` which returns a new stereo audio segment panned left/right as specified.

# v0.12.0
- Add a logger, `"pydub.converter"` which logs the ffmpeg commands being run by pydub.
- Add `pydub.AudioSegment().split_to_mono()` method which returns a list of mono audio segments. One for each channel in the original audio segment.
- Fix a bug in `pydub.silence.detect_silence()` which caused the function to break when a silent audio segment was equal in length to the minimum silence length. It should report a single span of silence covering the whole silent audio segment. Now it does.
- Fix a bug where uncommon wav formats (those not supported by the stdlib wave module) would throw an exception rather than converting to a more common format via ffmpeg/avconv

# v0.11.0
- Add `pydub.AudioSegment().max_dBFS` which reports the loudness (in dBFS) of the loudest point (i.e., highest amplitude sample) of an audio segment

# v0.10.0
- Overhaul Documentation
- Improve performance of `pydub.AudioSegment().overlay()`
- Add `pydub.AudioSegment().invert_phase()` which (shocker) inverts the phase of an audio segment
- Fix a type error in `pydub.AudioSegment.get_sample_slice()`

# v0.9.5
- Add `pydub.generators` module containing simple signal generation functions (white noise, sine, square wave, etc)
- Add a `loops` keyword argument to `pydub.AudioSegment().overlay()` which allows users to specify that the overlaid audio should be repeated (i.e., looped) a certain number of times, or indefinitely

# 0.9.4
- Fix a bug in db_to_float() where all values were off by a factor of 2

# 0.9.3
- Allow users to set the location of their converter by setting `pydub.AudioSegment.converter = "/path/to/ffmpeg"` and added a shim to support the old method of assigning to `pydub.AudioSegment.ffmpeg` (which is deprecated now that we support avconv)

# v0.9.2
- Add support for Python 3.4
- Audio files opened with format "wave" are treated as "wav" and "m4a" are treated as "mp4"
- Add `pydub.silence` module with simple utilities for detecting and removing silence.
- Fix a bug affecting auto-detection of ffmpeg/avconv on windows.
- Fix a bug that caused pydub to only work when ffmpeg/avconv is present (it should be able to work with WAV data without any dependencies)

# v0.9.1
- Add a runtime warning when ffmpeg/avconv cannot be found to aid debugging

# v0.9.0
- Added support for pypy (by reimplementing audioop in python). Also, we contributed our implementation to the pypy project, so that's 💯
- Add support for avconv as an alternative to ffmpeg
- Add a new helper module `pydub.playback` which allows you to quickly listen to an audio segment using ffplay (or avplay)
- Add new function `pydub.utils.mediainfo('/path/to/audio/file.ext')` which reports back the results of ffprobe (or avprobe) including codec, bitrate, channels, etc
61 changes: 61 additions & 0 deletions pydub/audio_segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,12 @@ def _spawn(self, data, overrides={}):
if isinstance(data, list):
data = b''.join(data)

if isinstance(data, array.array):
try:
data = data.tobytes()
except:
data = data.tostring()

# accept file-like objects
if hasattr(data, 'read'):
if hasattr(data, 'seek'):
Expand Down Expand Up @@ -753,6 +759,61 @@ def max_dBFS(self):
def duration_seconds(self):
return self.frame_rate and self.frame_count() / self.frame_rate or 0.0

def get_dc_offset(self, channel=1):
"""
Returns a value between -1.0 and 1.0 representing the DC offset of a
channel (1 for left, 2 for right).
"""
if not 1 <= channel <= 2:
raise ValueError("channel value must be 1 (left) or 2 (right)")

if self.channels == 1:
data = self._data
elif channel == 1:
data = audioop.tomono(self._data, self.sample_width, 1, 0)
else:
data = audioop.tomono(self._data, self.sample_width, 0, 1)

return float(audioop.avg(data, self.sample_width)) / self.max_possible_amplitude

def remove_dc_offset(self, channel=None, offset=None):
"""
Removes DC offset of given channel. Calculates offset if it's not given.
Offset values must be in range -1.0 to 1.0. If channel is None, removes
DC offset from all available channels.
"""
if channel and not 1 <= channel <= 2:
raise ValueError("channel value must be None, 1 (left) or 2 (right)")

if offset and not -1.0 <= offset <= 1.0:
raise ValueError("offset value must be in range -1.0 to 1.0")

if offset:
offset = int(round(offset * self.max_possible_amplitude))

def remove_data_dc(data, off):
if not off:
off = audioop.avg(data, self.sample_width)
return audioop.bias(data, self.sample_width, -off)

if self.channels == 1:
return self._spawn(data=remove_data_dc(self._data, offset))

left_channel = audioop.tomono(self._data, self.sample_width, 1, 0)
right_channel = audioop.tomono(self._data, self.sample_width, 0, 1)

if not channel or channel == 1:
left_channel = remove_data_dc(left_channel, offset)

if not channel or channel == 2:
right_channel = remove_data_dc(right_channel, offset)

left_channel = audioop.tostereo(left_channel, self.sample_width, 1, 0)
right_channel = audioop.tostereo(right_channel, self.sample_width, 0, 1)

return self._spawn(data=audioop.add(left_channel, right_channel,
self.sample_width))

def apply_gain(self, volume_change):
return self._spawn(data=audioop.mul(self._data, self.sample_width,
db_to_float(float(volume_change))))
Expand Down
20 changes: 7 additions & 13 deletions pydub/effects.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,8 @@ def apply_mono_filter_to_each_channel(seg, filter_fn):
for sample_i, sample in enumerate(channel_seg.get_array_of_samples()):
index = (sample_i * n_channels) + channel_i
out_data[index] = sample
try:
return seg._spawn(out_data.tobytes())
except:
return seg._spawn(out_data.tostring())

return seg._spawn(out_data)


@register_pydub_effect
Expand Down Expand Up @@ -225,10 +223,8 @@ def low_pass_filter(seg, cutoff):
offset = (i * seg.channels) + j
last_val[j] = last_val[j] + (alpha * (original[offset] - last_val[j]))
filteredArray[offset] = int(last_val[j])
try:
return seg._spawn(data=filteredArray.tobytes())
except:
return seg._spawn(data=filteredArray.tostring())

return seg._spawn(data=filteredArray)


@register_pydub_effect
Expand Down Expand Up @@ -260,12 +256,10 @@ def high_pass_filter(seg, cutoff):

last_val[j] = alpha * (last_val[j] + original[offset] - original[offset_minus_1])
filteredArray[offset] = int(min(max(last_val[j], minval), maxval))
try:
return seg._spawn(data=filteredArray.tobytes())
except:
return seg._spawn(data=filteredArray.tostring())


return seg._spawn(data=filteredArray)


@register_pydub_effect
def pan(seg, pan_amount):
"""
Expand Down
11 changes: 4 additions & 7 deletions pydub/scipy_effects.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
Of course, you will need to install scipy for these to work.
When this module is imported the high and low pass filters from this module
will be used when calling audio_segment.high_pass_filter() and
audio_segment.high_pass_filter() instead of the slower, less powerful versions
will be used when calling audio_segment.high_pass_filter() and
audio_segment.high_pass_filter() instead of the slower, less powerful versions
provided by pydub.effects.
"""
from scipy.signal import butter, sosfilt
Expand Down Expand Up @@ -41,10 +41,7 @@ def filter_fn(seg):
sos = butter(order, freqs, btype=type, output='sos')
y = sosfilt(sos, seg.get_array_of_samples())

try:
return seg._spawn(y.astype(seg.array_type).tobytes())
except:
return seg._spawn(y.astype(seg.array_type).tostring())
return seg._spawn(y.astype(seg.array_type))

return filter_fn

Expand All @@ -64,4 +61,4 @@ def high_pass_filter(seg, cutoff_freq, order=5):
@register_pydub_effect
def low_pass_filter(seg, cutoff_freq, order=5):
filter_fn = _mk_butter_filter(cutoff_freq, 'lowpass', order=order)
return seg.apply_mono_filter_to_each_channel(filter_fn)
return seg.apply_mono_filter_to_each_channel(filter_fn)
4 changes: 4 additions & 0 deletions pydub/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@ def mediainfo(filepath):

rgx = re.compile(r"(?:(?P<inner_dict>.*?):)?(?P<key>.*?)\=(?P<value>.*?)$")
info = {}

if sys.platform == 'win32':
output = output.replace("\r", "")

for line in output.split("\n"):
# print(line)
mobj = rgx.match(line)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

setup(
name='pydub',
version='0.16.6',
version='0.16.7',
author='James Robert',
author_email='jiaaro@gmail.com',
description='Manipulate audio with an simple and easy high level interface',
Expand Down
Binary file added test/data/test-dc_offset.wav
Binary file not shown.
Loading

0 comments on commit 99d910c

Please sign in to comment.