import string
from scipy.io import wavfile as wav
import numpy as np
import sounddevice as sd
import math 

print("Portfolio assignment 1: Clipped")
print("This program will create (overwrite) sine.wav and clipped.wav per specification\n and will play clipped.wav to the default audio output")

min_amp = np.iinfo(np.int16).min # = -32767
max_amp = np.iinfo(np.int16).max # = 32767

sample_rate = 48000 # samples/second

def generate(amp: float):
    frequency = 440 # cycles/second aka Hz
    duration = 1 # seconds
    time = np.linspace(0, duration, int(sample_rate * duration), endpoint=False) # array of discrete time values
    angle = 2 * np.pi * frequency * time # radians 2π(f * t)
    wave = amp * max_amp * np.sin(angle)
    return wave.astype(np.int16)

def write(wave, name: string):
    wav.write(name, sample_rate, wave)
    
def play(wave):
    sd.play(wave, samplerate=sample_rate, blocking=True, loop=False)

sine = generate(0.25)
clipped = np.clip(generate(0.5), math.floor(min_amp/4.0), math.ceil(max_amp/4.0))

write(sine,'sine.wav')
write(clipped,'clipped.wav')
play(clipped)