Skip to content

Instantly share code, notes, and snippets.

@cmdneo
Created December 23, 2019 12:34

Revisions

  1. cmdneo created this gist Dec 23, 2019.
    47 changes: 47 additions & 0 deletions retro-rocket.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    """Formula used: Frequency / Sample_rate * 10 * math.sqrt(x)
    x is [0, Duration * Sample_rate)
    """

    import wave
    import struct
    import math


    def fpart(val):
    """Returns fractional part of the number"""
    return val - int(val)


    class Sound():
    def __init__(self, frequency, duration, volume=1, channels=1):
    self.volume = volume * (2 ** 15 - 1)
    self.frequency = frequency
    self.channels = channels
    self.duration = duration

    SAMPLE_RATE = 44100
    BYTES_PER_FRAME = 2


    def main():
    s = Sound(8_000, 2)
    fconst = s.frequency / Sound.SAMPLE_RATE

    # Init code
    f = wave.open("test.wav", "wb")
    f.setnchannels(s.channels)
    f.setsampwidth(Sound.BYTES_PER_FRAME)
    f.setframerate(Sound.SAMPLE_RATE)

    for x in range(int(s.duration * Sound.SAMPLE_RATE)):
    value = int(
    s.volume * fpart(fconst * 10 * math.sqrt(x))
    )
    f.writeframesraw(struct.pack("<h", value))

    print(s.frequency)
    f.writeframes(b"")


    if __name__ == "__main__":
    main()