1-- simple script to set music / audio playback
2-- keys used:
3-- a. fade background music to 0
4-- b. fade background music to 1
5-- c. quick- play sample
6-- d. spawn 'background.ogg' stream
7-- e. kill background music
8
9sample_countdown = 0;
10sample = load_asample("soundtest.wav");
11playback = sample;
12
13bgmusic_id = 0;
14symtable = {}
15local tones = {
16	440.0,
17	466.16,
18	493.88,
19	523.25,
20	554.37,
21	587.33,
22	622.25,
23	659.26,
24	698.46,
25	739.99,
26	783.99,
27	830.61
28}
29
30local function build_sine(freq, length)
31	local step = 2 * math.pi * freq / 48000.0
32	local samples = length * 48000.0
33	local res = {}
34	local val = 0
35
36	for i=1,samples,2 do
37		res[i] = math.sin(val)
38		res[i+1] = res[i]
39		val = val + step
40	end
41
42	return res
43end
44
45function soundtest()
46	local sfun = system_load("builtin/keyboard.lua");
47	symtable = sfun();
48
49	for i=1,#tones do
50		local tbl = build_sine(tones[i], 1)
51		tones[i] = load_asample(tbl)
52	end
53
54	vid = render_text(
55	[[\ffonts/default.ttf,14\#ffffffSoundtest:\n\r\bKey:\tAction:\!b\n\r]] ..
56	[[(1..9)\tset sample to tone\n\r]] ..
57	[[c     \tset sample to wav\n\r]] ..
58	[[d     \tqueue sample\n\r]] ..
59	[[p     \tplaback sample\n\r]] ..
60	[[ESCAPE\tshutdown\n\r]]
61	);
62
63	playback = sample
64	show_image(vid);
65end
66
67local queue = {}
68function queue_next()
69	print("sample over, queue: ", #queue)
70	local ent = table.remove(queue)
71	if not ent then
72		return
73	end
74	play_audio(ent, queue_next)
75end
76
77function soundtest_input( inputtbl )
78	if (inputtbl.kind == "digital" and inputtbl.active and inputtbl.translated) then
79		local sym = symtable[ inputtbl.keysym ]
80		local num = tonumber(sym)
81
82		if num and tones[num] then
83			playback = tones[num]
84			print("playback set to", num)
85			if #queue > 0 then
86				print("queued")
87				table.insert(queue, playback)
88			end
89
90		elseif sym == "c" then
91			playback = sample
92
93		elseif sym == "d" then
94			table.insert(queue, playback)
95
96		elseif sym == "p" then
97			print("play", playback)
98			play_audio(playback, 1.0, queue_next)
99
100		elseif (symtable[ inputtbl.keysym ] == "f") then
101		    if (sample_countdown > 0) then
102			sample_countdown = 0;
103			print("disabling sample spam");
104		    else
105			print("enabling sample spam");
106			sample_countdown = 15;
107		    end
108
109		elseif  (symtable[ inputtbl.keysym ] == "ESCAPE") then
110		    shutdown();
111		end
112	end
113end
114
115function soundtest_clock_pulse()
116	if (sample_countdown > 0) then
117		sample_countdown = sample_countdown - 1;
118		if (sample_countdown == 0) then
119			play_audio(sample);
120			sample_countdown = 15;
121		end
122	end
123end
124
125function soundtest_audio_event( source, argtbl )
126  print(" [ Audio Event ]");
127  print("-> source" .. source);
128  print("-> kind" .. argtbl.kind);
129  print(" [---  End  ---]");
130  print(" ");
131end
132