import wave
fp = wave.open("passport.wav", 'r')
print fp
<wave.Wave_read instance at 0x795d950>
print fp.getframerate(), fp.getnchannels(), fp.getnframes(), fp.getsampwidth(), fp.getcomptype(), fp.getcompname()
44100 1 331098 2 NONE not compressed
fp.getparams()
(1, 2, 44100, 331098, 'NONE', 'not compressed')
bytes = fp.readframes(8)
print bytes
Y � � � � � ����
for byte in bytes:
print ord(byte),
89 0 225 0 182 0 137 0 188 0 129 0 252 255 179 255
for byte in bytes:
print bin(ord(byte)),
0b1011001 0b0 0b11100001 0b0 0b10110110 0b0 0b10001001 0b0 0b10111100 0b0 0b10000001 0b0 0b11111100 0b11111111 0b10110011 0b11111111
import struct
struct.unpack("hhhhhhhh", bytes)
(89, 225, 182, 137, 188, 129, -4, -77)
fp.rewind()
samples = []
for i in range(fp.getnframes()):
s = fp.readframes(1)
samples.append(struct.unpack('h', s))
plot(samples)
[<matplotlib.lines.Line2D at 0x21b20f10>]
samples = np.array(samples)
samplesnorm = samples/2**15
plot(samplesnorm)
[<matplotlib.lines.Line2D at 0x21afd4d0>]
plot(samplesnorm)
xlim((0, 100))
(0, 100)
samplesnorm = samples/2.0**15
plot(samplesnorm)
[<matplotlib.lines.Line2D at 0x1bac6690>]
print samples.dtype
print samplesnorm.dtype
int64 float64
outfile = wave.open('testout.wav','w')
outfile.getframerate()
--------------------------------------------------------------------------- Error Traceback (most recent call last) <ipython-input-220-ff2c2d70eb4c> in <module>() ----> 1 outfile.getframerate() /usr/lib/python2.7/wave.pyc in getframerate(self) 361 def getframerate(self): 362 if not self._framerate: --> 363 raise Error, 'frame rate not set' 364 return self._framerate 365 Error: frame rate not set
sr = 44100
outfile.setframerate(sr)
outfile.getnchannels()
--------------------------------------------------------------------------- Error Traceback (most recent call last) <ipython-input-222-e6d44c48a4cf> in <module>() ----> 1 outfile.getnchannels() /usr/lib/python2.7/wave.pyc in getnchannels(self) 337 def getnchannels(self): 338 if not self._nchannels: --> 339 raise Error, 'number of channels not set' 340 return self._nchannels 341 Error: number of channels not set
outfile.setnchannels(1)
outfile.getnchannels()
1
outfile.getsampwidth()
--------------------------------------------------------------------------- Error Traceback (most recent call last) <ipython-input-224-4931e2bff9db> in <module>() ----> 1 outfile.getsampwidth() /usr/lib/python2.7/wave.pyc in getsampwidth(self) 349 def getsampwidth(self): 350 if not self._sampwidth: --> 351 raise Error, 'sample width not set' 352 return self._sampwidth 353 Error: sample width not set
outfile.setsampwidth(2)
outfile.getsampwidth()
2
dur = 1.0
phase = linspace(0, 2*pi, dur*sr)
out = sin(phase)*2**15
for sample in out:
outfile.writeframes(struct.pack('h', int(sample)))
outfile.close()
outfile = wave.open('testout2.wav','w')
sr = 44100
outfile.setframerate(sr)
outfile.setnchannels(1)
outfile.setsampwidth(2)
freq = 440
dur = 1.0
phase = linspace(0, 2*pi, dur*sr)
out = sin(phase*freq)*2**15
for sample in out:
outfile.writeframes(struct.pack('h', int(sample)))
outfile.close()
Pros:
Cons:
# Great audio player for ipython notebook I found at http://nbviewer.ipython.org/github/Carreau/posts/blob/master/07-the-sound-of-hydrogen.ipynb
# The original source is here: https://github.com/Carreau/posts
import StringIO
import base64
import struct
from IPython.core.display import HTML
def wavPlayer(data, rate):
""" will display html 5 player for compatible browser
The browser need to know how to play wav through html5.
there is no autoplay to prevent file playing when the browser opens
Adapted from SciPy.io.
"""
buffer = StringIO.StringIO()
buffer.write(b'RIFF')
buffer.write(b'\x00\x00\x00\x00')
buffer.write(b'WAVE')
buffer.write(b'fmt ')
if data.ndim == 1:
noc = 1
else:
noc = data.shape[1]
bits = data.dtype.itemsize * 8
sbytes = rate*(bits // 8)*noc
ba = noc * (bits // 8)
buffer.write(struct.pack('<ihHIIHH', 16, 1, noc, rate, sbytes, ba, bits))
# data chunk
buffer.write(b'data')
buffer.write(struct.pack('<i', data.nbytes))
if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and sys.byteorder == 'big'):
data = data.byteswap()
buffer.write(data.tostring())
size = buffer.tell()
buffer.seek(4)
buffer.write(struct.pack('<i', size-8))
val = buffer.getvalue()
src = """
<body>
<audio controls="controls" style="width:600px" >
<source controls src="data:audio/wav;base64,{base64}" type="audio/wav" />
Your browser does not support the audio element.
</audio>
</body>
""".format(base64=base64.encodestring(val))
display(HTML(src))
A better option, but too new:
from IPython.display import Audio
Audio(url="http://www.nch.com.au/acm/8k16bitpcm.wav")
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-229-5dba57334beb> in <module>() ----> 1 from IPython.display import Audio 2 Audio(url="http://www.nch.com.au/acm/8k16bitpcm.wav") ImportError: cannot import name Audio
rate = 44100 #44.1 khz
duration = 2.5 # in sec
def normedsin(f,t):
return 2**14*sin(2*pi*f*t)
time = np.linspace(0,duration, num=rate*duration)
wavPlayer(normedsin(440, time).astype(np.int16), rate)
rate = 44100 #44.1 khz
duration = 1 # in sec
time = np.linspace(0,duration, num=rate*duration)
wavPlayer(normedsin(880, time).astype(np.int16), rate)
wavPlayer(samples.astype(np.int16), fp.getframerate())
wavPlayer(samples.astype(np.int16), 48000)
from scipy.io import wavfile
sr, frames = wavfile.read('passport.wav')
print sr
44100
plot(frames)
[<matplotlib.lines.Line2D at 0x21abc190>]
frames.dtype
dtype('int16')
wavPlayer(frames, sr)
Pros:
Cons:
from essentia.standard import AudioLoader
loader = AudioLoader(filename='passport.wav')
audio, sr, nchnls = loader()
plot(audio);
A numpy array, already normalized!
audio.shape, audio.dtype
((331098, 2), dtype('float32'))
wavPlayer(audio.astype(int16), sr)
wavPlayer((audio*2**15).astype(int16), sr)
wavPlayer((audio[:,0]*2**15).astype(int16), sr)
Essentia has a selection of audio loaders:
Essentia in Python tutorial: http://essentia.upf.edu/documentation/python_tutorial.html
loader = AudioLoader(filename='/home/andres/Music/Jose Vicente Asuar/Obra Electroacustica I/01. Variaciones espctrales (1959).flac')
audio, sr, nchnls = loader()
plot(audio[:44100])
[<matplotlib.lines.Line2D at 0x1babde90>, <matplotlib.lines.Line2D at 0x1bacae90>]
wavPlayer(audio, sr)
Fails! Too big!
wavPlayer((audio[:444100]*2.0**15).astype(int16), sr)
Pros:
Cons:
By Andrés Cabrera mantaraya36@gmail.com
For course MAT 240E at UCSB
This ipython notebook is licensed under the CC-BY-NC-SA license: http://creativecommons.org/licenses/by-nc-sa/4.0/