您的位置:首页 > 其它

利用libmad解码mp3

2011-08-31 10:13 417 查看
mp3是流媒体,所以一个完整文件往往比较大而且不能一次装入sound缓存,所以其buffer管理就成了最大难题,至于解码部分其实还是很简单的,下面是仅关于解码部分的说明

首先应该在自己的工程中包含以下三个库:

libid3tag-0.15.1b
libmad-0.15.1b
libz-1.1.4

必要的三个结构体及相关的初始化

view plaincopy
to clipboardprint?

mad_stream stream;
mad_frame frame;
mad_synth synth;
mad_stream_init(&stream);
mad_frame_init(&frame);
mad_synth_init(&synth);

view plaincopy
to clipboardprint?

mad_stream_buffer(&stream, buffer, buffer_size);

mad_stream_buffer(&stream, buffer, buffer_size);


对压缩数据进行解码,这里将控制着一个双层的循环逻辑

view plaincopy
to clipboardprint?

mad_frame_decode(&frame, &stream);

view plaincopy
to clipboardprint?

id3_tag_query(stream.this_frame, stream.bufend - stream.this_frame);
if(tagsize > 0)
{
mad_stream_skip(&stream, tagsize);
}

id3_tag_query(stream.this_frame, stream.bufend - stream.this_frame);
if(tagsize > 0)
{
mad_stream_skip(&stream, tagsize);
}

将解码数据转换为设备所能接受的pcm数据

view plaincopy
to clipboardprint?

mad_synth_frame(&synth, &frame);

view plaincopy
to clipboardprint?

for(int i = 0; i < (int)synth.pcm.length; i++)
{
sample0 = audio_linear_dither(16, synth.pcm.samples[0][i], &left_dither, &stats);
sample1 = audio_linear_dither(16, synth.pcm.samples[1][i], &right_dither, &stats);
tempBuffer[0] = sample0 >> 0;
tempBuffer[1] = sample0 >> 8;
tempBuffer[2] = sample1 >> 0;
tempBuffer[3] = sample1 >> 8;
}

for(int i = 0; i < (int)synth.pcm.length; i++)
{
sample0 = audio_linear_dither(16, synth.pcm.samples[0][i], &left_dither, &stats);
sample1 = audio_linear_dither(16, synth.pcm.samples[1][i], &right_dither, &stats);
tempBuffer[0] = sample0 >> 0;
tempBuffer[1] = sample0 >> 8;
tempBuffer[2] = sample1 >> 0;
tempBuffer[3] = sample1 >> 8;
}

单声道的转换方式

view plaincopy
to clipboardprint?

register int sample0;
for(int i = 0; i < (int)synth.pcm.length; i++)
{
sample0 = audio_linear_dither(16, synth.pcm.samples[0][i], &left_dither, &stats);
tempBuffer[0] = sample0 >> 0;
tempBuffer[1] = sample0 >> 8;
}

view plaincopy
to clipboardprint?

mad_synth_finish(&synth);
mad_frame_finish(&frame);
mad_stream_finish(&stream);

mad_synth_finish(&synth);
mad_frame_finish(&frame);
mad_stream_finish(&stream);

再举例一个基于looping结构的direct sound buffer管理机制:



详细代码可以参考我写的一个工程:
http://code.google.com/p/myt3dlib/source/browse/trunk/myGame/src/myResource.cpp?spec=svn110&r=110#478
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: