'##
'##  A simple sound generator
'##
'##  Public Domain software
'##
'##

'## internal PlayWav can't play files from memory
Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (lpszName As long, hModule As Long, dwFlags As Long) As Long


declare sub play

dim soundstream as qmemorystream
application.title = "Test"

create form as qform
	clientheight = 85'45
	clientwidth = 120
	center
	borderstyle = 3
	caption = "Sound"

	create label as qlabel
		top     = 5
		left    = 5
		width   = 100
		height  = 15
		caption = "Volume:"
	end create
	create trackbar as qtrackbar
		top      = 20
		left     = 5
		width    = 110
		height   = 22
		tickstyle = 0
		max      = 100
		position = 90
	end create

	create playbutton as qcoolbtn
		caption = "Play"
		top     = 55
		left    = 5
		height  = 25
		width   = 110
		onclick = play
	end create
end create

form.showmodal


sub play
	playbutton.caption = "Wait..."
	doevents

	'## stop sound and delete it
	playsound(0, 0, 0)
	soundstream.close

	soundstream.writestr("RIFF", 4) '## indicates wave file header chunk
	soundstream.writenum(640032, 4) '## total length of package to follow, 4 bytes

	soundstream.writestr("WAVE", 4)

	soundstream.writestr("fmt ", 4) '## begin format chunk
	soundstream.writenum(16, 4)     '## length of format chunk
	soundstream.writenum(1,  2)     '## WAVE_FORMAT_PCM
	soundstream.writenum(2,  2)     '## channels 1-mono 2-stereo
	soundstream.writenum(44100,  4) '## sample rate in Hz
	soundstream.writenum(176400, 4) '## bytes per second (samplerate * channels * bytespersample)
	soundstream.writenum(2,  2)     '## bytes per sample
	soundstream.writenum(16, 2)     '## bits per sample

	soundstream.writestr("data", 4) '## begin data chunk
	soundstream.writenum(640000, 4) '## length of data to follow

	'## generate a sound
	'## 160000 samples * 2 bytes * 2 channels = 640000 bytes
	for t = 1 to 160000
		'## I know, it isn't very nice, but it's simple
		'## use "+" instead of "xor" for clean mixing of frequencies
		soundstream.writenum((cos(t / 51) xor sin(t / 150)) * (t / 160000)            * (163.83 * trackbar.position), 2) '## left channel
		soundstream.writenum((sin(t / 51) xor cos(t / 150)) * ((160000 - t) / 160000) * (163.83 * trackbar.position), 2) '## right channel
	next

	'## play from memory
	playsound(soundstream.pointer, 0, 5)

	playbutton.caption = "Play"
end sub

