Skip to content

Instantly share code, notes, and snippets.

@kenial
Last active July 29, 2022 18:49
Show Gist options
  • Save kenial/dced727f51c91288459a108323321d4f to your computer and use it in GitHub Desktop.
Save kenial/dced727f51c91288459a108323321d4f to your computer and use it in GitHub Desktop.
make 1 second length random wave sound (PCM) file.
import random
def get_wave_data():
s = "52494646" # RIFF
s += "88580100" # subchunks. 88,200 in hex, little-endian
s += "57415645" # "WAVE" chunk identifier
s += "666d7420" # "fmt " chunk identifier
s += "10000000" # length of chunk, 16
s += "0100" # format code (PCM)
s += "0200" # channel
s += "22560000" # sample rate. 22,050 in hex, little-endian
s += "88580100" # byterate.
s += "0400" # block align
s += "1000" # bits per sample (16)
s += "64617461" # "data" start of chunk
s += "88580100" # length of chunk. 88,200
for i in range(88200):
s += f"{random.randint(0,255):02x}"
i = 0
while True:
subt = s[i:i+2]
if not subt:
break
yield subt
i += 2
wave_data = list(get_wave_data())
f = open("test.wav", "wb")
for c in wave_data:
f.write(bytes((int(c, 16),)))
f.close()
@nethomas1968
Copy link

s += f"{random.randint(0,255):02x}"

Syntax error??

@nethomas1968
Copy link

Oh, wait, it's something new in Python. Sorry.

@kenial
Copy link
Author

kenial commented Jan 12, 2022

@nethomas1968 / yeah new formatting as of py3.6 :)

@nethomas1968
Copy link

Hi, thanks, also can you explain these lines please:
s += "88580100" # 88,236 in decimal
s += "88580100" # 88200 in decimal

Cheers.

@kenial
Copy link
Author

kenial commented Jul 29, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment