Experimental Notebook#
I thought it’d be a good idea to leave a space on this website with some empty code blocks that you can use to copy/edit any small snippet of code, experiment with an idea, or try to code up some particular concept you’ve encountered to get a better understanding of it. Just run the first cell below to import all of the packages (you may want to add some as needed). You can then click “add cell” to add more code blocks as you like.
An important thing to remember is that if you leave the page, your code will be lost! So if you do develop something cool, be sure to copy and paste it somewhere to save it. If you want to copy and paste code from some other notebooks, then I recommend opening those notebooks in a new tab and then copy/paste into here. Have fun!
# Hit the live python code button and firstly run this cell to import several of the packages you may want to use.
# Feel free to add more packages as needed, but re-run this cell
%pip install ipympl
import numpy as np
import scipy as sp
import io
from scipy.io import wavfile
import matplotlib
if not hasattr(matplotlib.RcParams, "_get"):
matplotlib.RcParams._get = dict.get
from pyodide.http import pyfetch
from matplotlib import pyplot as plt
from ipywidgets import * # interactive plots
import IPython
from IPython.display import Audio, Image
%matplotlib ipympl
# function for reading WAV files from a URL. Must be a RAW link, not GitHub HTML
speech_sample = "https://raw.githubusercontent.com/randyaliased/acspjbook/main/book/audio/F2.wav"
impulse_resp = "https://raw.githubusercontent.com/randyaliased/acspjbook/main/book/audio/IR1.wav"
async def read_wav_from_url(url):
response = await pyfetch(url)
wav_bytes = await response.bytes() # get raw binary
fs, data = wavfile.read(io.BytesIO(wav_bytes))
# convert to float in [-1, 1]
if np.issubdtype(data.dtype, np.integer):
max_val = np.iinfo(data.dtype).max
data = data.astype(np.float32) / max_val
else:
data = data.astype(np.float32) # already float
return data, fs
# This is an open notebook, feel free to write and experiment with your own code here.
# I've left some commented out code below that you can use as a starting point if you want to do a simple interactive plot.
# fig, axes = plt.subplots(figsize=(8,4))
# dt = 0.00001 # time spacing
# t = np.arange(0,2,dt) # range of times to plot on x-axis
# line, = axes.plot([], [], 'k')
# axes.set_ylabel('Amplitude', color='k')
# axes.set_xlabel('Time (s)', color='k')
# axes.set_xlim([0, 0.01])
# axes.set_ylim([-1, 1])
# # Create the interactive plot
# def update_sinusoid(A = 1, fo=100, theta = 0):
# fig.canvas.draw_idle()
# y = A*np.cos(2*np.pi*fo*t + theta)
# line.set_data(t, y)
# IPython.display.display(Audio(y.T, rate=1/dt,normalize=False))
# interact(update_sinusoid, A = (0.1,1,0.1), fo = (0,2000,10), theta = (0,2*np.pi,np.pi/10));
# plt.show()