I am trying to build a python synthesizer using pygame.
I followed some tutorials and combined some code from different sources, but when playing the output as a sound, I get random noise for different frequencies.
Here is the code with irrelevant parts ommitted:
import key_manager as km
from array import array
import pygame
from pygame import mixer
from pygame.mixer import Sound, get_init, pre_init
import time
import numpy as np
import math
class Note(pygame.mixer.Sound):
def __init__(self, frequency, volume=.1):
self.frequency = frequency
if synth_type == "sine":
Sound.__init__(self, self.build_samples_sine())
self.set_volume(volume)
def build_samples_sine(self):
period = int(round(get_init()[0] / self.frequency))
samples = array("h", [0] * period * 2)
amplitude = 2 ** (abs(get_init()[1]) - 1) - 1
for time in range(period * 2):
samples[time] = int(round(amplitude * math.sin(2 * math.pi * self.frequency * time)))
return samples
pre_init(44100, -16, 1, 1024)
pygame.init()
frequency = <whatever frequency I am trying to play>
mixer.Channel(frequency).play(note, -1)
Thanks for any help or advice.