1music = {
2	thread = love.thread.newThread("musicthread", "musicloader_thread.lua"),
3	toload = {},
4	loaded = {},
5	list = {},
6	list_fast = {},
7	pitch = 1,
8}
9
10music.stringlist = table.concat(music.toload, ";")
11
12function music:init()
13	self.thread:start()
14end
15
16function music:load(musicfile) -- can take a single file string or an array of file strings
17	if type(musicfile) == "table" then
18		for i,v in ipairs(musicfile) do
19			self:preload(v)
20		end
21	else
22		self:preload(musicfile)
23	end
24	self.stringlist = table.concat(self.toload, ";")
25	self.thread:set("musiclist", self.stringlist)
26end
27
28function music:preload(musicfile)
29	if self.loaded[musicfile] == nil then
30		self.loaded[musicfile] = false
31		table.insert(self.toload, musicfile)
32	end
33end
34
35function music:play(name)
36	if name and soundenabled then
37		if self.loaded[name] == false then
38			local source = self.thread:demand(name)
39			self:onLoad(name, source)
40		end
41		if self.loaded[name] then
42			playsound(self.loaded[name])
43		end
44	end
45end
46
47function music:playIndex(index, isfast)
48	local name = isfast and self.list_fast[index] or self.list[index]
49	self:play(name)
50end
51
52function music:stop(name)
53	if name and self.loaded[name] then
54		love.audio.stop(self.loaded[name])
55	end
56end
57
58function music:stopIndex(index, isfast)
59	local name = isfast and self.list_fast[index] or self.list[index]
60	self:stop(name)
61end
62
63function music:update()
64	for i,v in ipairs(self.toload) do
65		local source = self.thread:get(v)
66		if source then
67			self:onLoad(v, source)
68		end
69	end
70	for name, source in pairs(self.loaded) do
71		if source ~= false then
72			source:setPitch(self.pitch)
73		end
74	end
75	local err = self.thread:get("error")
76	if err then print(err) end
77end
78
79function music:onLoad(name, source)
80	self.loaded[name] = source
81	source:setLooping(true)
82	source:setPitch(self.pitch)
83end
84
85
86music:load{
87	"overworld",
88	"overworld-fast",
89	"underground",
90	"underground-fast",
91	"castle",
92	"castle-fast",
93	"underwater",
94	"underwater-fast",
95	"starmusic",
96	"starmusic-fast",
97	"princessmusic",
98}
99
100-- the original/default music needs to be put in the correct lists
101for i,v in ipairs(music.toload) do
102	if v:match("fast") then
103		table.insert(music.list_fast, v)
104	elseif not v:match("princessmusic") then
105		table.insert(music.list, v)
106	end
107end
108
109music:init()
110
111