LuaYard/Music.cpp

112 lines
2.2 KiB
C++
Raw Permalink Normal View History

#include "Music.h"
#include "LuaCommon.h"
#include "LuaHelper.h"
#include <iostream>
using namespace std;
Mix_Chunk* Mix_LoadWAVEx(const char* filepath)
{
SDL_RWops* fileData = SDL_RWFromFile(filepath, "rb");
if (!fileData)
{
std::cout << "Mix_LoadWAVEx() failed to call SDL_RWFromFile().\n\t\"" << SDL_GetError() << "\"" << std::endl;
return NULL;
}
Mix_Chunk* chunk = Mix_LoadWAV_RW(fileData, 1);
if (!chunk)
{
std::cout << "Mix_LoadWAVEx() failed to call Mix_LoadWAV_RW().\n\t\"" << SDL_GetError() << "\"" << std::endl;
return NULL;
}
return chunk;
}
inline int Chunk::close(lua_State* L)
{
auto p = (Chunk*)luaL_checkudata(L, 1, "chunk");
p->~Chunk();
return 0;
}
int Chunk::create(lua_State* L)
{
cout << "In Chunk::create" << endl;
const char* filepath = luaL_checkstring(L, 1);
Mix_Chunk* c = Mix_LoadWAVEx(filepath);
if (!c)
{
return LuaSDLError(L);
}
auto p = new (lua_newuserdata(L, sizeof(Chunk))) Chunk(c);
if (luaL_newmetatable(L, "chunk"))
{
// GC
lua_pushcfunction(L, close);
lua_setfield(L, -2, "__gc");
// Fields
lua_newtable(L);
settype("chunk");
setfn(close, "close");
lua_setfield(L, -2, "__index");
}
lua_setmetatable(L, -2);
return 1;
}
inline int Chunk::setVolume(lua_State* L)
{
auto p = (Chunk*)luaL_checkudata(L, 1, "chunk");
int v = luaL_checkinteger(L, 2);
int old = Mix_VolumeChunk(p->chunk.get(), v);
lua_pushinteger(L, old);
return 1;
}
inline Chunk::Chunk(Mix_Chunk* c) : chunk(c, Mix_FreeChunk)
{
}
inline Music::Music(Mix_Music* m) : music(m, Mix_FreeMusic)
{
}
inline int Music::close(lua_State* L)
{
cout << "In Music::close" << endl;
auto p = (Music*)luaL_checkudata(L, 1, "music");
p->~Music();
return 0;
}
int Music::create(lua_State* L)
{
cout << "In Music::create" << endl;
const char* filepath = luaL_checkstring(L, 1);
Mix_Music* m = Mix_LoadMUS(filepath);
if (!m)
{
return LuaSDLError(L);
}
auto p = new (lua_newuserdata(L, sizeof(Music))) Music(m);
if(luaL_newmetatable(L, "music"))
{
// GC
lua_pushcfunction(L, close);
lua_setfield(L, -2, "__gc");
// Fields
lua_newtable(L);
settype("music");
setfn(close, "close");
lua_setfield(L, -2, "__index");
}
lua_setmetatable(L, -2);
return 1;
}