#include <Python.h>
#include <lame.h> //pyton object variables
typedef struct{
PyObject_HEAD
FILE *outfp;
lame_global_flags *gfp;
} pylame2_EncoderObject; static PyObject *Encoder_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
pylame2_EncoderObject *self = (pylame2_EncoderObject *)type->tp_alloc(type, );
self->outfp = NULL;
self->gfp = NULL;
return (PyObject *)self;
} static void Encoder_dealloc(pylame2_EncoderObject *self)
{
if(self->gfp)
{
lame_close(self->gfp);
}
if(self->outfp)
{
fclose(self->outfp);
}
self->ob_type->tp_free(self);
} static int Encoder_init(pylame2_EncoderObject * self, PyObject *args, PyObject *kw)
{
char *outpath;
if(!PyArg_ParseTuple(args, "s", &outpath))
{
return -;
}
if(self->outfp || self->gfp)
{
PyErr_SetString(PyExc_Exception, "__init__ already called");
return -;
}
self->outfp = fopen(outpath, "wb");
self->gfp = lame_init();
lame_init_params(self->gfp);
return ;
} static PyObject *Encoder_encode(pylame2_EncoderObject *self, PyObject *args)
{
char *in_buffer;
int in_length;
int mp3_length;
char *mp3_buffer;
int mp3_bytes;
if(!(self->outfp && self->gtp))
{
PyErr_SetString(PyExc_Exception, "encoder not open");
return NULL;
}
if(!PyArg_ParseTuple(args, "s#", &in_buffer, &in_length))
{
return NULL;
}
in_length /=;
mp3_length = (int)(1.25 * in_length) + ;
mp3_buffer = (char*)malloc(mp3_length);
if(in_length > )
{
mp3_bytes = lame_encode_buffer_interleaved(
self->gtp,
(short *)in_buffer,
in_length / ,
mp3_buffer,
mp3_length
);
if(mpe3_bytes > )
{
fwrite(mp3_buffer, , mp3_bytes, self->outfp);
}
}
free(mp3_buffer);
Py_RETURN_NONE;
}
static PyObject *Encoder_close(pylame2_EncoderObject * self)
{
int mp3_length;
char * mp3_buffer;
int mpe3_bytes;
if(!(self->outfp && self->gfp))
{
PyErr_SetString(PyExc_Exception, "encoder not open");
return NULL;
}
mp3_length = ;
mp3_buffer = (char*)malloc(mp3_length);
mp3_bytes = lame_encode_flush(self->gfp, mp3_buffer, sizeof(mp3_buffer));
if(mp3_bytes > )
{
fwrite(mp3_buffer, , mp3_bytes, self->outfp);
}
free(mp3_buffer);
lame_close(self->gfp);
self->gfp = NULL;
fclose(self->outfp);
self->outfp = NULL;
Py_RETURN_NONE;
}
static PyMethodDef Encoder_methods[] ={
{"encode", (PyCFunction)Encoder_encode, METH_VARARGS, "Encodes and writes data to the output file."},
{"close", (PyCFunction)Encoder_close, METH_NOARGS, "Closes the output file."},
{NULL, NULL, , NULL}
};
static PyTypeObject pylame2_EncoderType = {
PyObject_HEAD_INIT(NULL)
, /* ob_size */
"pylame2.Encoder", /* tp_name */
sizeof(pylame2_EncoderObject), /* tp_basicsize */
, /* tp_itemsize */
(destructor)Encoder_dealloc, /* tp_dealloc */
, /* tp_print */
, /* tp_getattr */
, /* tp_setattr */
, /* tp_compare */
, /* tp_repr */
, /* tp_as_number */
, /* tp_as_sequence */
, /* tp_as_mapping */
, /* tp_hash */
, /* tp_call */
, /* tp_str */
, /* tp_getattro */
, /* tp_setattro */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"My first encoder object.", /* tp_doc */
, /* tp_traverse */
, /* tp_clear */
, /* tp_richcompare */
, /* tp_weaklistoffset */
, /* tp_iter */
, /* tp_iternext */
Encoder_methods, /* tp_methods */
, /* tp_members */
, /* tp_getset */
, /* tp_base */
, /* tp_dict */
, /* tp_descr_get */
, /* tp_descr_set */
, /* tp_dictoffset */
(initproc)Encoder_init, /* tp_init */
, /* tp_alloc */
Encoder_new, /* tp_new */
, /* tp_free */
}; static PyMethodDef pylame2_methods[] = {
{NULL, NULL, , NULL}
}; PyMODINIT_FUNC initpylame2(){
PyObject *m;
if(PyType_Ready(&pylame2_EncoderType) < )
{
return;
}
m = Py_InitModule3("pylame2", pylame2_methods, "My Second LAME module.");
Py_INCREF(&pylame2_EncoderType);
PyModule_AddObject(m, "Encoder", (PyObject *)&pylame2_EncoderType);
}; /*
gcc -shared -I/usr/include/pytyon3.1 -I/usr/include/lame pylame2.c -lmp3lame -o pylame2.so
*/
/*python code
import pylame2 INBUFSIZE = 4096 encoder = pylame2.Encoder('test.mp3')
input = file('test.raw', 'rb')
data = input.read(INBUFSIZE) while data != '':
encoder.encode(data)
data = input.read(INBUFSIZE) input.close()
encoder.close()
*/

use the python object's methods in c code

#include <Python.h>
#include <lame.h> //pyton object variables
typedef struct{
PyObject_HEAD
//FILE *outfp;
PyObject *outfp;
lame_global_flags *gfp;
} pylame2_EncoderObject; static PyObject *Encoder_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
pylame2_EncoderObject *self = (pylame2_EncoderObject *)type->tp_alloc(type, );
self->outfp = NULL;
self->gfp = NULL;
return (PyObject *)self;
} static void Encoder_dealloc(pylame2_EncoderObject *self)
{
if(self->gfp)
{
lame_close(self->gfp);
}
/*
if(self->outfp)
{
fclose(self->outfp);
}*/
Py_XDECREF(self->outfp);
self->ob_type->tp_free(self);
} static int Encoder_init(pylame2_EncoderObject * self, PyObject *args, PyObject *kw)
{
//char *outpath;
PyObject *outfp;
if(!PyArg_ParseTuple(args, "O", &outfp))
{
return -;
}
if(self->outfp || self->gfp)
{
PyErr_SetString(PyExc_Exception, "__init__ already called");
return -;
}
//self->outfp = fopen(outpath, "wb");
self->outfp = outfp;
Py_INCREF(self->outfp);
self->gfp = lame_init();
lame_init_params(self->gfp);
return ;
} static PyObject *Encoder_encode(pylame2_EncoderObject *self, PyObject *args)
{
char *in_buffer;
int in_length;
int mp3_length;
char *mp3_buffer;
int mp3_bytes;
if(!(self->outfp && self->gtp))
{
PyErr_SetString(PyExc_Exception, "encoder not open");
return NULL;
} if(!PyArg_ParseTuple(args, "s#", &in_buffer, &in_length))
{
return NULL;
}
in_length /=;
mp3_length = (int)(1.25 * in_length) + ;
mp3_buffer = (char*)malloc(mp3_length); if(in_length > )
{
mp3_bytes = lame_encode_buffer_interleaved(
self->gtp,
(short *)in_buffer,
in_length / ,
mp3_buffer,
mp3_length
);
if(mpe3_bytes > )
{
//fwrite(mp3_buffer, 1, mp3_bytes, self->outfp);
PyObject * write_result = PyObject_CallMethod(self->outfp, "write", "(s#)", mp3_buffer, mp3_bytes);
if(!write_result)
{
free(mp3_buffer);
return NULL;
}
Py_DECREF(write_result);
}
}
// free(mp3_buffer);
// Py_RETURN_NONE;
}
static PyObject *Encoder_close(pylame2_EncoderObject * self)
{
int mp3_length;
char * mp3_buffer;
int mpe3_bytes;
if(!(self->outfp && self->gfp))
{
PyErr_SetString(PyExc_Exception, "encoder not open");
return NULL;
}
mp3_length = ;
mp3_buffer = (char*)malloc(mp3_length);
mp3_bytes = lame_encode_flush(self->gfp, mp3_buffer, sizeof(mp3_buffer));
if(mp3_bytes > )
{
fwrite(mp3_buffer, , mp3_bytes, self->outfp);
}
free(mp3_buffer);
lame_close(self->gfp);
self->gfp = NULL;
fclose(self->outfp);
self->outfp = NULL;
Py_RETURN_NONE;
}
static PyMethodDef Encoder_methods[] ={
{"encode", (PyCFunction)Encoder_encode, METH_VARARGS, "Encodes and writes data to the output file."},
{"close", (PyCFunction)Encoder_close, METH_NOARGS, "Closes the output file."},
{NULL, NULL, , NULL}
};
static PyTypeObject pylame2_EncoderType = {
PyObject_HEAD_INIT(NULL)
, /* ob_size */
"pylame2.Encoder", /* tp_name */
sizeof(pylame2_EncoderObject), /* tp_basicsize */
, /* tp_itemsize */
(destructor)Encoder_dealloc, /* tp_dealloc */
, /* tp_print */
, /* tp_getattr */
, /* tp_setattr */
, /* tp_compare */
, /* tp_repr */
, /* tp_as_number */
, /* tp_as_sequence */
, /* tp_as_mapping */
, /* tp_hash */
, /* tp_call */
, /* tp_str */
, /* tp_getattro */
, /* tp_setattro */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"My first encoder object.", /* tp_doc */
, /* tp_traverse */
, /* tp_clear */
, /* tp_richcompare */
, /* tp_weaklistoffset */
, /* tp_iter */
, /* tp_iternext */
Encoder_methods, /* tp_methods */
, /* tp_members */
, /* tp_getset */
, /* tp_base */
, /* tp_dict */
, /* tp_descr_get */
, /* tp_descr_set */
, /* tp_dictoffset */
(initproc)Encoder_init, /* tp_init */
, /* tp_alloc */
Encoder_new, /* tp_new */
, /* tp_free */
}; static PyMethodDef pylame2_methods[] = {
{NULL, NULL, , NULL}
}; PyMODINIT_FUNC initpylame2(){
PyObject *m;
if(PyType_Ready(&pylame2_EncoderType) < )
{
return;
}
m = Py_InitModule3("pylame2", pylame2_methods, "My Second LAME module.");
Py_INCREF(&pylame2_EncoderType);
PyModule_AddObject(m, "Encoder", (PyObject *)&pylame2_EncoderType);
}; /*
gcc -shared -I/usr/include/pytyon3.1 -I/usr/include/lame pylame2.c -lmp3lame -o pylame2.so
*/
/*python code
import pylame2 INBUFSIZE = 4096 class MyFile(file):
def __init__(self, path, mode):
file.__init__(self, path, mode)
self.n = 0 def write(self, s):
file.write(self, s)
self.n += 1 output = MyFile('test3.mp3', 'wb')
encoder = pylame2.Encoder(output)
input = file('test.raw', 'rb') data = input.read(INBUFSIZE)
while data !='':
encoder.encode(data)
data = input.read(INBUFSIE) input.close()
encoder.close()
output.close() print("output.write was called %d times" % output.n)
*/

python c example2:pylame2的更多相关文章

  1. (转载) 浅谈python编码处理

    最近业务中需要用 Python 写一些脚本.尽管脚本的交互只是命令行 + 日志输出,但是为了让界面友好些,我还是决定用中文输出日志信息. 很快,我就遇到了异常: UnicodeEncodeError: ...

  2. 使用Python将HTML转成PDF

    主要使用的是wkhtmltopdf的Python封装--pdfkit 安装 1. Install python-pdfkit: $ pip install pdfkit 2. Install wkht ...

  3. python——协程

    由于python中的多线程比较特殊,所以协程的概念就变得尤为珍贵了,对于cpu密集型的操作,使用协程的效率无疑要好过多线程很多.因为协程的创建及其间切换的时间成本要低于线程很多.也因为这一点,很多人说 ...

  4. Python(文件、文件夹压缩处理模块,shelve持久化模块,xml处理模块、ConfigParser文档配置模块、hashlib加密模块,subprocess系统交互模块 log模块)

    OS模块 提供对操作系统进行调用的接口 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname")  改变当前脚本工作目 ...

  5. python学习笔记-Day6(2)

    xml处理模块 xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融 ...

  6. Python:如何显示进度条

    首先,推荐一个组件:progressive 效果如下: 进度条和一般的print区别在哪里呢? 答案就是print会输出一个\n,也就是换行符,这样光标移动到了下一行行首,接着输出,之前已经通过std ...

  7. Think Python - Chapter 11 - Dictionaries

    Dictionaries A dictionary is like a list, but more general. In a list, the indices have to be intege ...

  8. python多线程threading

    本文通过 4个example 介绍python中多线程package —— threading的常用用法, 包括调用多线程, 同步队列类Queue, Ctrl+c结束多线程. example1. 调用 ...

  9. 一行 Python 实现并行化 -- 日常多线程操作的新思路

    春节坐在回家的火车上百无聊赖,偶然看到 Parallelism in one line 这篇在 Hacker News 和 reddit 上都评论过百的文章,顺手译出,enjoy:-) http:// ...

随机推荐

  1. 【数论】【筛法求素数】【欧拉函数】bzoj2818 Gcd

    gcd(x,y)(1<=x,y<=n)为素数(暂且把(x,y)和(y,x)算一种) 的个数 <=> gcd(x/k,y/k)=1,k是x的质因数 的个数 <=> Σ ...

  2. Atom | 报错 Cannot load the system dictionary for zh-CN的解决办法

    文章目录 问题描述 推荐阅读 查找问题所在 解决方案 (二选一) 问题描述 最近这款优秀的编辑器 atom,报错 Cannot load the system dictionary for zh-CN ...

  3. mysql获取分类数量

    1.sql <select id="getTypeNum" resultType="TypeNum" > select count(*) as al ...

  4. pythonGUI编程打开默认浏览器

    代码: from tkinter import * import webbrowser root = Tk() text = Text(root,width=30,height = 5) text.p ...

  5. 如何用JavaScript重定向到另一个网页?

    可以使用 window.location.replace() 方法重定向到另一个页面.相对于 window.location.href ,replace的优势是不会跳转记录并不会保留在历史会话中,这就 ...

  6. pdf.js 添加自定义loading动画

    最近做了个手机端pdf预览的功能,用到pdf.js这个库,效果还不错.但是在网络差.文件大时,页面一直空白,体验不是很好. 于是加了个loading动画. <div id="loadi ...

  7. FL2440 Linux-3.0内核触摸屏的支持

    ---------------------------------------------------------------------------------------------------- ...

  8. 【招聘App】—— React/Nodejs/MongoDB全栈项目:项目准备

    前言:最近在学习Redux+react+Router+Nodejs全栈开发高级课程,这里对实践过程作个记录,方便自己和大家翻阅.最终成果github地址:https://github.com/66We ...

  9. webmagic的多线程及线程池的应用

  10. 基础普及-Jar、War、Ear

    名词解释 Jar文件(扩展名为. Jar) 包括Java类的普通库.资源(resources).辅助文件 (auxiliary files)等 War文件(扩展名为.War) 包括所有Web应用程序. ...