I have a jupyter notebook file and a .wav file that I am working with. You can find both here:
https://github.com/diggetybo/ICA-Attachments
I have created python functions to load a .wav
file and play it using an HTML interface within jupyter notebook.
I will repurpose this post slightly becuase I have resolved the load_wav function. What remains unresolved is the other function, wavPlayer. It supposed to take a numpy representation of a .wav file and render it for playback. Unfortunately, it's not working at all. All the files, despite being correctly loaded by load_wav, have the error: 'This audio content is encoded by an unsupported format.' And doesn't play. Clearly, in this link, the original author of the code had it working:
My guess is it's a version compatibility issue. I use Python 3.5, this tutorial was in 2.7 I think.
All I need to be able to accept an answer to this question is for someone to get a .wav file to be played by the wavPlayer function in Python 3.5 (see either link for the jupyter notebook file) My guess after a week of playing around with it is the StringIO and/or BytesIO sections of the code. I'm not an expert on those particular libraries, so I'm hoping someone can help out here.
For accessibility purposes, I'll post the function below.
import sys
import StringIO
import base64
import struct
from IPython.display import display
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. and
github.com/Carreau/posts/blob/master/07-the-sound-of-hydrogen.ipynb
"""
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())
# return buffer.getvalue()
# Determine file size and place it in correct
# position at start of the file.
size = buffer.tell()
buffer.seek(4)
buffer.write(struct.pack('<i', size-8))
val = buffer.getvalue()
src = """
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Simple Test</title>
</head>
<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))
Thank you