Last active
February 19, 2020 02:25
-
-
Save anibalsolon/91560ba0b02f45cd09ad0d61eb4326ba to your computer and use it in GitHub Desktop.
Listening to audio on Jupyter notebooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
import base64 | |
import numpy as np | |
from IPython.core.display import HTML | |
from scipy.io import loadmat, wavfile | |
data = loadmat('./sounds.mat')['sounds'] | |
test = loadmat('./icaTest.mat') | |
def player(wave, bitrate=11025): | |
# convert to PCM (some browsers does not support) | |
if wave.dtype in [np.float32, np.float64]: | |
wave = (wave * 32767).astype(np.int16) | |
fh = io.BytesIO() | |
wavfile.write(fh, bitrate, wave) | |
enc = base64.b64encode(fh.read()).decode('ascii') | |
display(HTML(f''' | |
<audio controls="controls"> | |
<source src="data:audio/wav;base64,{enc}" type="audio/wav" /> | |
Your browser does not support audio. | |
</audio> | |
''')) | |
# For Jupyter notebook/lab | |
player(data[0]) | |
# For listening in a sound player | |
wavfile.write('myaudio.wav', rate=11025, data=data[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment