2 Copyright (c)2006-2007 - 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
= MIX_DEFAULT_FREQUENCY
; //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
= 512; //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);
52 if(Mix_PlayChannel(-1, s
, 0)==-1){
53 Mix_AllocateChannels(Mix_AllocateChannels(-1)+1);
54 Mix_PlayChannel(-1, s
, 0);
60 int l_stopsamples(lua_State
*L
){
66 int l_loadsample(lua_State
*L
){
68 std::map
<std::string
, Mix_Chunk
*>::iterator s
= sample_cache
.find(std::string(luaL_checkstring(L
,1)));
70 if( s
== sample_cache
.end()){
71 temp
= Mix_LoadWAV(luaL_checkstring(L
,1));
72 sample_cache
[std::string(luaL_checkstring(L
,1))] = temp
;
75 lua_pushlightuserdata(L
,temp
);
80 int l_unloadsample(lua_State
*L
){
81 std::map
<std::string
, Mix_Chunk
*>::iterator s
= sample_cache
.find(std::string(luaL_checkstring(L
,1)));
82 if(s
!= sample_cache
.end()){
83 Mix_FreeChunk(s
->second
);
84 sample_cache
.erase(s
);
89 //clear the sample cache
90 int l_clearsamples(lua_State
*L
){
91 std::map
<std::string
, Mix_Chunk
*>::iterator s
= sample_cache
.begin();
92 for( ; s
!= sample_cache
.end(); s
++){
93 Mix_FreeChunk(s
->second
);
101 int l_playmusic(lua_State
*L
){
102 std::string temp
= std::string(luaL_checkstring(L
,1));
103 //free up music if not free
105 if(Mix_PlayingMusic())
107 if(temp
!= _music_filename
){ //only free if not loaded
108 Mix_FreeMusic(_music
);
111 if(temp
!= _music_filename
){ //only load if not loaded
112 _music
= Mix_LoadMUS(temp
.c_str());
113 _music_filename
= temp
;
116 //don't halt on error, just output it
118 std::cerr
<< "ERROR: Cannot load music file '" << luaL_checkstring(L
,1) << "' : " << Mix_GetError();
121 Mix_PlayMusic(_music
, lua_tointeger(L
,2));
127 int l_stopmusic(lua_State
*L
){
130 Mix_FreeMusic(_music
);
131 _music_filename
= "";