fm-modulator/signalgen.py
2023-01-01 13:34:40 -08:00

51 lines
1.4 KiB
Python

import math
class SignalGenerator:
def __init__(
self,
frequency,
amplitude,
sample_rate,
output_range=(-1, 1),
convert_to_int=False,
):
self.phase = 0
self.frequency = frequency
self.amplitude = amplitude
self.sample_rate = sample_rate
self.output_range = output_range
self.convert_to_int = convert_to_int
def sample(self):
sample = math.sin(self.phase * math.tau) * self.amplitude
self.phase += self.frequency / self.sample_rate
self.phase %= 1
return (int if self.convert_to_int else float)(
remap(sample, -1, 1, self.output_range[0], self.output_range[1])
)
def generate_samples(self, samples):
return [self.sample() for _ in range(samples)]
def generate_time(self, time):
return self.generate_samples(round(time * self.sample_rate))
def remap(number, from_min, from_max, to_min, to_max):
number_s = number - from_min
from_max_s = from_max - from_min
to_max_s = to_max - to_min
return ((number_s / from_max_s) * to_max_s) + to_min
g = SignalGenerator(0, 1, 48000, (0, 255), True)
with open("input.raw", "rb") as f:
data = list(f.read())
with open("output.raw", "wb+") as f:
for d in data:
g.frequency = ((d / 255) * 12500) + 4000
f.write(bytes(g.generate_samples(6)))