# create music.prg from music.wav: python.exe sampler.py

import wave
import binascii
import array
import struct

# output data array
prgData = bytearray()

# add sampler (from "sampler.prg" file)
#samplerFile = open('sampler.prg', 'rb')
#sampler = samplerFile.read()
#prgData += bytearray(sampler)

# hexdump sampler
#print ''.join( [ "%02X " % ord( x ) for x in sampler ] ).strip()

# add sampler inline
prgData += bytearray.fromhex(
	'01 08 0F 08 DD 07 9E 20 BD 28 37 2E 36 34 29 00 00 00 00 00 00 00 00 00 00 00 00' +
	'00 00 00 00 00 78 A9 35 85 01 A2 00 8E 11 D0 A9 70 85 57 A9 08 85 58 86 59 86 5A' +
	'A5 59 CD 6E 08 D0 07 A5 5A CD 6F 08 F0 E6 A1 57 48 29 0F 8D 18 D4 A0 14 88 D0 FD' +
	'68 6A 6A 6A 6A 29 0F 8D 18 D4 A0 12 88 D0 FD E6 59 D0 02 E6 5A E6 57 D0 CC E6 58' +
	'4C 35 08')

# load samples
waveFile = wave.open('music8khz.wav', 'r')
length = waveFile.getnframes()

# add sample size
prgData.append(int(length / 2) & 0xff)
prgData.append(int(length / 2 / 0x100))

# add samples
def sampleToFourBit(sample):
	s = struct.unpack("<h", sample)[0]
	return int((s + 32768) * 16 / 65536)

for i in range(0,int(length / 2)):
	low = sampleToFourBit(waveFile.readframes(1))
	high = sampleToFourBit(waveFile.readframes(1))
	prgData.append(low | (high << 4))
    
# save PRG
prg = open('music.prg', 'wb')
prg.write(prgData)
prg.close()
