Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Just an experimemt with sound. Produces a sound similar to used in old games. Formula: 10 * sqrt(x)
"""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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment