2 Copyright (c)2006-2008 - Brett Lajzer
4 See LICENSE for license information.
9 #include "funcs_sound.h"
12 static const int mix_channels
= 16; //the number of mixing channels
13 static const int mix_rate
= 44100; //the mix rate in Hz
14 static const int mix_format
= MIX_DEFAULT_FORMAT
; //the output format
15 static const int mix_op_channels
= 2; //output channels, 2 == stereo
16 static const int mix_chunksize
= 256; //output chunk size
21 //Attempt to open the audio device in this format
22 if(Mix_OpenAudio(mix_rate
, mix_format
, mix_op_channels
, mix_chunksize
)==-1){
23 std::cerr
<< "ERROR: Couldn't Initialize SoundEngine: " << Mix_GetError() << "\n";
28 Mix_AllocateChannels(mix_channels
);
36 //free music if loaded
38 Mix_FreeMusic(_music
);
40 //free up the samples in the sample cache
41 for(std::map
<std::string
, Mix_Chunk
*>::iterator it
= sample_cache
.begin(); it
!= sample_cache
.end(); it
++)
42 Mix_FreeChunk(it
->second
);
50 int l_playsample(lua_State
*L
){
51 Mix_Chunk
*s
= (Mix_Chunk
*)lua_touserdata(L
,1);
54 return luaL_error(L
, "ERROR: Can't play sample, is NULL.");
57 if(Mix_PlayChannel(-1, s
, 0)==-1){
58 Mix_AllocateChannels(Mix_AllocateChannels(-1)+1);
59 Mix_PlayChannel(-1, s
, 0);
65 int l_stopsamples(lua_State
*L
){
71 int l_loadsample(lua_State
*L
){
73 std::map
<std::string
, Mix_Chunk
*>::iterator s
= sample_cache
.find(std::string(luaL_checkstring(L
,1)));
75 if( s
== sample_cache
.end()){
76 temp
= Mix_LoadWAV(luaL_checkstring(L
,1));
79 return luaL_error(L
, "ERROR: Can't find sound file: \"%s\".", luaL_checkstring(L
,1));
82 sample_cache
[std::string(luaL_checkstring(L
,1))] = temp
;
85 lua_pushlightuserdata(L
,temp
);
90 int l_unloadsample(lua_State
*L
){
91 std::map
<std::string
, Mix_Chunk
*>::iterator s
= sample_cache
.find(std::string(luaL_checkstring(L
,1)));
92 if(s
!= sample_cache
.end()){
93 Mix_FreeChunk(s
->second
);
94 sample_cache
.erase(s
);
99 //clear the sample cache
100 int l_clearsamples(lua_State
*L
){
101 std::map
<std::string
, Mix_Chunk
*>::iterator s
= sample_cache
.begin();
102 for( ; s
!= sample_cache
.end(); s
++){
103 Mix_FreeChunk(s
->second
);
105 sample_cache
.clear();
111 int l_playmusic(lua_State
*L
){
112 std::string temp
= std::string(luaL_checkstring(L
,1));
113 //free up music if not free
115 if(Mix_PlayingMusic())
117 if(temp
!= _music_filename
){ //only free if not loaded
118 Mix_FreeMusic(_music
);
121 if(temp
!= _music_filename
){ //only load if not loaded
122 _music
= Mix_LoadMUS(temp
.c_str());
123 _music_filename
= temp
;
126 //don't halt on error, just output it
128 return luaL_error(L
, "ERROR: Can't load music file \"%s\" : %s.",luaL_checkstring(L
,1), Mix_GetError());
131 Mix_PlayMusic(_music
, lua_tointeger(L
,2));
137 int l_stopmusic(lua_State
*L
){
140 Mix_FreeMusic(_music
);
141 _music_filename
= "";