Skip to content

Instantly share code, notes, and snippets.

@reflechant
Last active January 24, 2016 19:49
Show Gist options
  • Save reflechant/c6e4e67f0e2e945f4194 to your computer and use it in GitHub Desktop.
Save reflechant/c6e4e67f0e2e945f4194 to your computer and use it in GitHub Desktop.
Generate 440Hz (note A) wave file on Windows with Python
import mmap
import winsound as ws
import struct as st
from math import sin, cos, radians
from random import randint
# in RIFF format (and therefore in WAVE) ALL NUMBERS ARE LITTLE ENDIAN
FILE_SIZE = 44100*10+44 # bytes
FREQ = 440 # Hz
SAMPLE_FREQ = 44100 # Hz
#s = mmap.mmap(-1, FILE_SIZE)
s = open("1.wav", "wb")
s.write(b"RIFF") # 4B
s.write( st.pack("<I", FILE_SIZE-8) ) # file size - 8
s.write(b"WAVE") # 4B
s.write(b"fmt ")
s.write( st.pack("<I", 0x10) ) # chunk data size - always 0x10
s.write( st.pack("<I", 0x00010001) ) # 2B compression code (0x01)
# and 2B channel numbers (0x01)
s.write( st.pack("<I", SAMPLE_FREQ) ) # 4B sample rate in Hz
s.write( st.pack("<I", SAMPLE_FREQ*2) ) # 4B Bytes/sec
# 2B Bytes/sample: 1=8bit mono;$ 2=8bit stereo OR 16bit mono; 4=16bit stereo
# 2B bits/sample
s.write( bytes.fromhex("02 00 10 00") )
#s.write( bytes[02,00,10,00] )
#s.write(b"\x02\x00\x10\x00")
s.write(b"data")
s.write( st.pack("<I", FILE_SIZE-11*4) ) # 4B length of data to follow
#sound samples
for i in range(int((FILE_SIZE-11*4) / 2)):
x = int( sin( radians( i * FREQ/(SAMPLE_FREQ/360/2) ) ) * 32767 )
#x = randint(0,65535) # white noise
s.write( st.pack( "<i", x ) )
s.close()
ws.PlaySound("1.wav", ws.SND_FILENAME)
#ws.PlaySound(s,ws.SND_MEMORY)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment