Broadcasting a NumPy array

Broadcasting a NumPy array refers to a procedure executed on two operands even if they don’t have the same shape.

In this example we are going to multiply a scalar and an array. We will import a sound file and we will make it quieter.

import scipy.io.wavfile as sw
import matplotlib.pyplot as plt
import urllib
import numpy as np

request = urllib.request.Request('http://www.thesoundarchive.com/austinpowers/smashingbaby.wav')
response = urllib.request.urlopen(request)
print(response.info())
WAV_FILE = 'smashingbaby.wav'
filehandle = open(WAV_FILE, 'wb')
filehandle.write(response.read())
filehandle.close()
sample_rate, data = sw.read(WAV_FILE)
print("Data type", data.dtype, "Shape", data.shape)

plt.subplot(2, 1, 1)
plt.title("Original")
plt.plot(data)

plt.show()

newdata = data * 0.2
newdata = newdata.astype(np.uint8)
print("Data type", newdata.dtype, "Shape", newdata.shape)

sw.write("quiet.wav", sample_rate, newdata)

plt.subplot(2, 1, 2)
plt.title("Quiet")
plt.plot(newdata)

plt.show()

The output:

Content-Type: audio/wav
Last-Modified: Tue, 12 Aug 2014 15:53:38 GMT
Accept-Ranges: bytes
ETag: "ac20ba9445b6cf1:0"
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Tue, 26 Sep 2017 22:32:35 GMT
Connection: close
Content-Length: 43642


Data type uint8 Shape (43584,)
Data type uint8 Shape (43584,)

Broadcasting a NumPy array
Broadcasting a NumPy array quieter

Explanations:

Reading the WAV file

We use standard Python code to download a sound file (Austin Powers exclaiming “Smashing, baby.”) SciPy has a wavfile subpackage, which lets you load audio data or generate WAV files. This subpackage comes with the SciPy instalation.

The read() function delivers a data array and sample rate. We care only about the data here:

sample_rate, data = scipy.io.wavfile.read(WAV_FILE)

Plot the original WAV data

The following code plots the original data and gives the subplot the name “Original”.

plt.subplot(2, 1, 1)
plt.title("Original")
plt.plot(data)

Create a new array

First we have to produce a hushed sound sample which we can do it by creating a new array with smaller values by multiplying it with a constant. We have to make sure we have the same data type as in the original array.

newdata = data * 0.2
newdata = newdata.astype(np.uint8)

Write to a WAV file

This new array can be saved in a new WAV file:

scipy.io.wavfile.write("quiet.wav", sample_rate, newdata)

Plot the new WAV data

Plot the new data array with Matplotlib (there are two plt.show() one for the “Original” and one for “Quiet”):

plt.subplot(2, 1, 2)
plt.title("Quiet")
plt.plot(newdata)
plt.show()

The result is two diagrams of the two files, the original WAV file data and the modified WAV file (new array with smaller values).

Leave a Reply