# create music8.prg from music11khz.wav: python.exe sampler8.py
# required in the same directory: sampler8.prg

import wave
import binascii
import array
import struct

# output data array
prgData = bytearray()

# add sampler (from "sampler8.prg" file)
samplerFile = open('sampler8.prg', 'rb')
sampler = samplerFile.read()
prgData += bytearray(sampler)

# load samples
waveFile = wave.open('music11khz.wav', 'r')
length = waveFile.getnframes()
if (length + len(prgData) + 0x801 >= 0xd000):
	max = 0xd000 - 0x801 - len(prgData) + 1
	seconds = max / 11000.0
	print("error: WAV file too big, max sample count is " + str(0xd000 - 0x801 - len(prgData) + 1) + ", " + str(seconds) + " seconds @11kHz")
	exit(0)
blocks = int(length / 256)
if blocks * 256 < length: blocks = blocks + 1

# add sample size
prgData.append(blocks)

# add samples
def sampleToEightBit(sample):
	s = struct.unpack("<h", sample)[0]
	return int((s + 32768) * 256 / 65536)
for i in range(0, length):
	b = sampleToEightBit(waveFile.readframes(1))
	prgData.append(b)

# fill last block
for i in range(0, length - blocks * 256):
	prgData.append(128)
    
# save PRG
prg = open('music8.prg', 'wb')
prg.write(prgData)
prg.close()
