#include <Python.h>
#include <windows.h>
#include <mmsystem.h>

#pragma comment(lib, "winmm.lib")

// play sound
static PyObject* play(PyObject* self, PyObject* args)
{
    const char* filename;

    if (!PyArg_ParseTuple(args,"s",&filename))
        return NULL;

    PlaySound(filename,NULL,SND_FILENAME | SND_SYNC);

    Py_RETURN_NONE;
}

// stop sound
static PyObject* stop(PyObject* self, PyObject* args)
{
    PlaySound(NULL,NULL,0);
    Py_RETURN_NONE;
}

// set volume 0-100
static PyObject* volume(PyObject* self, PyObject* args)
{
    int v;

    if (!PyArg_ParseTuple(args,"i",&v))
        return NULL;

    if(v < 0) v = 0;
    if(v > 100) v = 100;

    DWORD vol = (DWORD)(v * 65535 / 100);
    DWORD volume = vol | (vol << 16);

    waveOutSetVolume(0,volume);

    Py_RETURN_NONE;
}

// delay then play
static PyObject* delay(PyObject* self, PyObject* args)
{
    int sec;
    const char* filename;

    if (!PyArg_ParseTuple(args,"is",&sec,&filename))
        return NULL;

    Sleep(sec * 1000);

    PlaySound(filename,NULL,SND_FILENAME | SND_SYNC);

    Py_RETURN_NONE;
}

static PyMethodDef Methods[] = {

    {"play",play,METH_VARARGS,"Play sound"},
    {"stop",stop,METH_VARARGS,"Stop sound"},
    {"volume",volume,METH_VARARGS,"Set volume"},
    {"delay",delay,METH_VARARGS,"Delay then play"},

    {NULL,NULL,0,NULL}
};

static struct PyModuleDef sondmodule = {

    PyModuleDef_HEAD_INIT,
    "sond",
    NULL,
    -1,
    Methods
};

PyMODINIT_FUNC PyInit_sond(void)
{
    return PyModule_Create(&sondmodule);
}