我試圖PCM聲音在Python一點點,但我已經試過包名太多或沒有證件或死了,所以我決定做一個簡單的一個與libao。禮包時爲Python模塊編譯例如不工作
我用作由xiph.org起點this source code播放440Hz的1秒,並且餘與gcc -o ao_example ao_example.c -lao -ldl -lm
編譯它,我成功運行該代碼,立即聽到440Hz的正弦以便在兩個通道1秒。
到目前爲止,這麼好。
所以我$ cp ao_exemple.c mySoundAo.c
和我編輯mySoundAo.c
被編譯爲Python模塊。完整的代碼如下:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <ao/ao.h>
#include <Python.h>
#define BUF_SIZE 4096
static PyObject* py_soundAo(PyObject* self, PyObject* args)
{
ao_device *device;
ao_sample_format format;
int default_driver;
char *buffer;
int buf_size;
int sample;
float freq = 440.0;
int i;
/* -- Initialize -- */
fprintf(stderr, "libao example program\n");
ao_initialize();
/* -- Setup for default driver -- */
default_driver = ao_default_driver_id();
memset(&format, 0, sizeof(format));
format.bits = 16;
format.channels = 2;
format.rate = 44100;
format.byte_format = AO_FMT_LITTLE;
/* -- Open driver -- */
device = ao_open_live(default_driver, &format, NULL /* no options */);
if (device == NULL) {
fprintf(stderr, "Error opening device.\n");
return Py_BuildValue("", 0);
}
/* -- Play some stuff -- */
buf_size = format.bits/8 * format.channels * format.rate;
buffer = calloc(buf_size,
sizeof(char));
for (i = 0; i < format.rate; i++) {
sample = (int)(0.75 * 32768.0 * sin(2 * M_PI * freq * ((float) i/format.rate)));
/* Put the same stuff in left and right channel */
buffer[4*i] = buffer[4*i+2] = sample & 0xff;
buffer[4*i+1] = buffer[4*i+3] = (sample >> 8) & 0xff;
}
ao_play(device, buffer, buf_size);
/* -- Close and shutdown -- */
ao_close(device);
ao_shutdown();
return Py_BuildValue("", 0);
}
static PyMethodDef mySoundAo_methods[] = {
{"soundAo", py_soundAo, METH_VARARGS},
{NULL, NULL}
};
void initmySoundAo()
{
(void) Py_InitModule("mySoundAo", mySoundAo_methods);
}
所以我編譯爲gcc -shared -I/usr/include/python2.7/ -o mySoundAo.so mySoundAo.c -lpython2.7 -lm -lsndfile -lao -ldl
,我有這樣的警告:
In file included from /usr/include/python2.7/Python.h:8:0,
from mySoundAo.c:5:
/usr/include/python2.7/pyconfig.h:1158:0: warning: "_POSIX_C_SOURCE" redefined [enabled by default]
/usr/include/features.h:214:0: note: this is the location of the previous definition
聽起來並不多危險,讓我感動的。
在Python中,我做了以下內容:
$ python
Python 2.7.2+ (default, Oct 4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mySoundAo
>>> mySoundAo.soundAo()
libao example program
Error opening device.
>>>
沒有聲音。檢查碼一點點,我發現了功能ao_initialize();
掛起約4第二和下面的行default_driver = ao_default_driver_id();
設置此變量爲-1(錯誤)。
此行爲是奇怪的,因爲它幾乎相同的代碼。
因此,任何想法,使這項工作?
謝謝!
優秀的問題。如果在'〜/ .libao.conf'中設置了'debug',你會發現'/ usr/lib/ao/plugins-4/libalsa.so'無法在Python上下文中加載。嘗試連接到NAS時,4秒延遲似乎是超時。你有沒有理由不使用[pyao](http://ekyo.nerim.net/software/pyogg/index.html)? – phihag
是的,@phihag我在這裏設置了調試,我看到了。有趣的...嗯,我不使用pyao,因爲它看起來像死了,因爲我沒有找到例子。但再看一看,我看到的代碼相對較短,所以我認爲我可以對其進行逆向工程以創建一個工作示例,謝謝! 但問題仍然存在:爲什麼上面的代碼不起作用? – LucasBr