Combining multiple waves to play more than one note at a time in python?

Viewed 416

I am trying to make a very basic program that can turn a midi file into a single waveform in python, so as a very basic test I used np.cos to generate a few waveforms, and then added them together, however, when I tried to use sounddevice to play the wave I generated, it sounded really strange. I am by no means an expert at all on sound and signal concepts; it's a pretty new subject to me, so any help is greatly appreciated.

Here is the code:

import sounddevice as sd
import numpy as np

def make_wave(freq, duration, sample_rate = 22050):
    wave = []
    for i in range(0,duration*sample_rate):
        wave.append(i/((sample_rate/(2*np.pi))/freq))

    wave = np.cos(np.stack(wave))
    return wave


            
A = make_wave(440, 10)
Cs = make_wave(554.37, 10)
E = make_wave(659.25, 10)


sd.play(A+Cs+E, 22050)
1 Answers

For people who actually so happen to have the same issue or similar issue of combining waves, it turns out it's actually a very simple problem; because the total amplitude added up is greater than 1, the computer audio freaks out, and some clipping occurs, causing the weird noise, so simply instead, I just needed to limit the amplitude to 0.1.

New code:

import sounddevice as sd
import numpy as np

def make_wave(freq, duration, sample_rate = 22050):
    wave = []
    for i in range(0,duration*sample_rate):
        wave.append(i/((sample_rate/(2*np.pi))/freq))

    wave = np.sin(np.stack(wave))
    return wave


            
A = make_wave(440, 10)
Cs = make_wave(554.37, 10)
E = make_wave(659.25, 10)

chord = A+Cs+E

chord = chord*0.1/np.max(chord)
sd.play(chord, 22050)

Hope I helped at least somebody by writing this!

Related