`
duyouhua1214
  • 浏览: 228029 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

采用libmad编写最简单的mp3播放器

 
阅读更多
libmad库中附带minimad,hige level API example,minimad执行使用minimad,再加上一些音频参数设置,即可实现一个简单的mp3播放程序;
首先:在minimad.c中加入以下代码,

# include <stdio.h>
# include <unistd.h>
# include <sys/stat.h>
# include <sys/mman.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
# include "mad.h"
#undef putchar

int soundfd;
int writedsp(int c) {
return write(soundfd, (char *)&c, 1);
}

void set_dsp()
{
int rate = 441000;;                /* 采样频率 44.1KHz*/
int format = AFMT_S16_LE; /*     量化位数 16      */
int channels = 2;                 /*     声道数 2           */

soundfd
= open ( "/dev/dsp", O_WRONLY);
ioctl(soundfd, SNDCTL_DSP_SPEED,
&rate);
ioctl(soundfd, SNDCTL_DSP_SETFMT,
&format);
ioctl(soundfd, SNDCTL_DSP_CHANNELS,
&channels);
}


修改minimad代码如下:
1.在main函数中解码前调用set_dsp(),解码结束后close(soundfd);

int main(int argc, char *argv[])
{
struct stat stat;
void *fdm;

if (argc != 1)
    return 1;

if (fstat(STDIN_FILENO, &stat) == -1 ||
      stat.st_size == 0)
    return 2;

fdm = mmap(0, stat.st_size, PROT_READ, MAP_SHARED, STDIN_FILENO, 0);
if (fdm == MAP_FAILED)
    return 3;

set_dsp(); //here

decode(fdm, stat.st_size);

if (munmap(fdm, stat.st_size) == -1)
    return 4;

close(soundfd); //here

return 0;
}

2.修改output函数中的putchar为writedsp:
enum mad_flow output(void *data,
             struct mad_header const *header,
             struct mad_pcm *pcm)
{
unsigned int nchannels, nsamples;
mad_fixed_t const *left_ch, *right_ch;

/* pcm->samplerate contains the sampling frequency */

nchannels = pcm->channels;
nsamples = pcm->length;
left_ch   = pcm->samples[0];
right_ch = pcm->samples[1];

while (nsamples--) {
    signed int sample;

    /* output sample(s) in 16-bit signed little-endian PCM */

    sample = scale(*left_ch++);
    writedsp((sample >> 0) & 0xff);
    writedsp((sample >> 8) & 0xff);

    if (nchannels == 2) {
      sample = scale(*right_ch++);
      writedsp((sample >> 0) & 0xff);
      writedsp((sample >> 8) & 0xff);
    }
}

return MAD_FLOW_CONTINUE;
}


播放命令:
#./minimad <music.mp3

结果:DBM上运行顺畅,而开发板上很卡,估计是AC97驱动还有待改善。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics