Skip to content

Commit

Permalink
If scipy is available, use it to open wav files
Browse files Browse the repository at this point in the history
This allows pydub to open files having more than 48KHz
and/or 32-bit data.

If scipy is not available, falls back to using the standard
wave module as before.

Fixes jiaaro#134
  • Loading branch information
antlarr committed Mar 23, 2018
1 parent 9db53a8 commit e231209
Showing 1 changed file with 25 additions and 13 deletions.
38 changes: 25 additions & 13 deletions pydub/audio_segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,19 +152,31 @@ def __init__(self, data=None, *args, **kwargs):
reader = data.read(2**31-1)
data = d

raw = wave.open(StringIO(data), 'rb')

raw.rewind()
self.channels = raw.getnchannels()
self.sample_width = raw.getsampwidth()
self.frame_rate = raw.getframerate()
self.frame_width = self.channels * self.sample_width

raw.rewind()

# the "or b''" base case is a work-around for a python 3.4
# see https://github.com/jiaaro/pydub/pull/107
self._data = raw.readframes(float('inf')) or b''
try:
import scipy.io.wavfile
except ImportError:
# scipy is not available so we use the standard wave module
raw = wave.open(StringIO(data), 'rb')
raw.rewind()
self.channels = raw.getnchannels()
self.sample_width = raw.getsampwidth()
self.frame_rate = raw.getframerate()
self.frame_width = self.channels * self.sample_width

raw.rewind()

# the "or b''" base case is a work-around for a python 3.4
# see https://github.com/jiaaro/pydub/pull/107
self._data = raw.readframes(float('inf')) or b''
else:
# We can use scipy, which supports more file formats than
# the wave module
raw = scipy.io.wavfile.read(StringIO(data))
self.channels = raw[1][0].size
self.sample_width = raw[1].dtype.itemsize
self.frame_rate = raw[0]
self.frame_width = self.channels * self.sample_width
self._data = raw[1].tobytes()

# Convert 24-bit audio to 32-bit audio.
# (stdlib audioop and array modules do not support 24-bit data)
Expand Down

0 comments on commit e231209

Please sign in to comment.