hd1

python libmpg123 wrapper

hd1
Mar 1st, 2014
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 KB | None | 0 0
  1. #include <mpg123.h>
  2. #include <ao.h>
  3. #include <Python.h>
  4.  
  5. #define BITS 8
  6.  
  7. static PyObject *mpg123_play(PyObject *self, PyObject *args) {
  8.   const char *command;
  9.   int sts;
  10.   if (!PyArg_ParseTuple(args, "s", &command))
  11.     return NULL;
  12.   sts = play(command);
  13.   return PyBuildValue("i", sts);
  14. }
  15.  
  16. int play(char *filename)
  17. {
  18.     mpg123_handle *mh;
  19.     unsigned char *buffer;
  20.     size_t buffer_size;
  21.     size_t done;
  22.     int err;
  23.  
  24.     int driver;
  25.     ao_device *dev;
  26.  
  27.     ao_sample_format format;
  28.     int channels, encoding;
  29.     long rate;
  30.  
  31.     /* initializations */
  32.     ao_initialize();
  33.     driver = ao_default_driver_id();
  34.     mpg123_init();
  35.     mh = mpg123_new(NULL, &err);
  36.     buffer_size = mpg123_outblock(mh);
  37.     buffer = (unsigned char*) malloc(buffer_size * sizeof(unsigned char));
  38.  
  39.     /* open the file and get the decoding format */
  40.     mpg123_open(mh, filename);
  41.     mpg123_getformat(mh, &rate, &channels, &encoding);
  42.  
  43.     /* set the output format and open the output device */
  44.     format.bits = mpg123_encsize(encoding) * BITS;
  45.     format.rate = rate;
  46.     format.channels = channels;
  47.     format.byte_format = AO_FMT_NATIVE;
  48.     format.matrix = 0;
  49.     dev = ao_open_live(driver, &format, NULL);
  50.  
  51.     /* decode and play */
  52.     while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
  53.         ao_play(dev, buffer, done);
  54.  
  55.     /* clean up */
  56.     free(buffer);
  57.     ao_close(dev);
  58.     mpg123_close(mh);
  59.     mpg123_delete(mh);
  60.     mpg123_exit();
  61.     ao_shutdown();
  62.  
  63. }
  64.  
  65. static PyMethodDef SpamMethods[] = {
  66.     {"play", mpg123_play, METH_VARARGS,
  67.      "play an mp3 file using libmpg123"},
  68.     {NULL, NULL, 0, NULL}        /* Sentinel */
  69. };
  70.  
  71. PyMODINIT_FUNC
  72. initmodule(void)
  73. {
  74.     (void) Py_InitModule("mpg123", SpamMethods);
  75. }
  76.  
  77. int main(int argc, char **argv) {
  78.   /* Pass argv[0] to the Python interpreter */
  79.   Py_SetProgramName(argv[0]);
  80.  
  81.   /* Initialize the Python interpreter.  Required. */
  82.   Py_Initialize();
  83.   initmodule();
  84.   return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment