soundwave.py: 22 points
At this point, we can finally create full songs. But let’s be real, they don’t sound great. That’s because we are only playing one note at a time. Fortunately, we can play multiple notes at the same time by simply adding, or superimposing, sound waves together.
Since we are adding two SoundWave
objects together, this is a perfect time for us to try overloading the +
operator. To overload the addition operator, we need to define a __add__()
method in our SoundWave
class. Specifically, we’ll add a method called __add__(self, s2)
to the end of our class definition—Python style suggests always putting methods which overload operators after class-specific methods.
Like the extend()
method you created in the previous part, __add__()
should take in another SoundWave
object, s2
, as a parameter. Unlike extend()
, however, the __add__()
method should create and return a new SoundWave
object, and leave the original two SoundWave
objects unchanged.
The samples of this new SoundWave
object created by the +
operator should be the sum (superposition) of the samples of s2
and the samples of self
. That is, the i
-th sample in the new SoundWave
should have a value equal to the sum of the i
-th samples of s2
and self
:
s.samples[i] = self.samples[i] + s2.samples[i]
Make sure that your program works even when self
and s2
have different lengths.
To test whether your overloaded __add__()
method is working, we have provided a program called surprise.py
. Running this program should create a new wave file called surprise.wav
that you can play similar to the middlec.wav
in the previous part of the lab. If your __add__()
method is working, you should hear the start of a song you might recognize…