前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >libmad学习进阶4 -----基于atlas音频驱动架构的MP3播放器

libmad学习进阶4 -----基于atlas音频驱动架构的MP3播放器

作者头像
用户4148957
发布于 2022-06-14 00:16:37
发布于 2022-06-14 00:16:37
8240
举报
文章被收录于专栏:C/C++与音视频C/C++与音视频

 /*modify by hfl 20140216*/ #define ALSA_PCM_NEW_HW_PARAMS_API # include <stdio.h> # include <unistd.h> # include <sys/stat.h> # include <sys/mman.h> # include "mad.h" #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<stdlib.h> #include <sys/ioctl.h> #include <sys/soundcard.h> #include <alsa/asoundlib.h> /*  * This is perhaps the simplest example use of the MAD high-level API.  * Standard input is mapped into memory via mmap(), then the high-level API  * is invoked with three callbacks: input, output, and error. The output  * callback converts MAD's high-resolution PCM samples to 16 bits, then  * writes them to standard output in little-endian, stereo-interleaved  * format.  */  //#define printf     static Get_file_length(char *PATH); static int init_dsp(); static int Uninit_dsp(); static int decode(unsigned char const *, unsigned long); static enum mad_flow outputplay(void *data,     struct mad_header const *header,     struct mad_pcm *pcm); int main(int argc, char *argv[]) { printf("The main is start!\n");   struct stat stat;   void *fdm;   int  fd;   //char buffer1[80000];   printf("###The input file is %s  ! the arc=%d###\n",argv[1],argc);   if (argc == 1)    {    printf("The argc is wrong!\n");     return 1;  } #if 0   if (fstat(STDIN_FILENO, &stat) == -1 ||       stat.st_size == 0)     return 2; #endif  fd =open(argv[1],O_RDWR); if(-1==fd) {    printf("sorry,The file open is faild!\n"); } else {  printf("The file open is sucessed!\n"); } //read(fd,buffer1,sizeof(buffer1)); //printf("%s", buffer1); stat.st_size = Get_file_length(argv[1]); printf("The file size is %d\n",stat.st_size ); printf("The Map is begin ok!\n"); fdm = mmap(0, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);   if (fdm == MAP_FAILED) { printf("mmap is failed\n");     return 3; }   decode(fdm, stat.st_size);   if (munmap(fdm, stat.st_size) == -1)     return 4;   return 0; } /*  * This is a private message structure. A generic pointer to this structure  * is passed to each of the callback functions. Put here any data you need  * to access from within the callbacks.  */ struct buffer {   unsigned char const *start;   unsigned long length; }; int id; int flag=0; snd_pcm_t *handle;  snd_pcm_uframes_t frames =1024;  int fd=0; /*初始化音频设备*/ int init_dsp(int rate,int channels) {   int rc;   snd_pcm_hw_params_t *params;   int dir;    /* Open PCM device for playback. */   rc = snd_pcm_open(&handle, "default",                     SND_PCM_STREAM_PLAYBACK, 0);   if (rc < 0) {     fprintf(stderr,             "unable to open pcm device: %s\n",             snd_strerror(rc));     exit(1);   }   /* Allocate a hardware parameters object. */   snd_pcm_hw_params_alloca(&params);   /* Fill it in with default values. */   snd_pcm_hw_params_any(handle, params);   /* Set the desired hardware parameters. */   /* Interleaved mode */   snd_pcm_hw_params_set_access(handle, params,                       SND_PCM_ACCESS_RW_INTERLEAVED);   /* Signed 16-bit little-endian format */   snd_pcm_hw_params_set_format(handle, params,                               SND_PCM_FORMAT_S16_LE);   /* Two channels (stereo) */   printf("channel=%d\n", channels);   snd_pcm_hw_params_set_channels(handle, params, channels);   /* 44100 bits/second sampling rate (CD quality) */  // val = 16000;   snd_pcm_hw_params_set_rate_near(handle, params,                                   & rate, &dir); printf("rate=%d\n",rate);   /* Set period size to 32 frames. */   /*一次送人的帧太少,会下溢冲(至少15帧)*/  // snd_pcm_hw_params_set_period_size_near(handle,  params, &frames, &dir);   /* Write the parameters to the driver */   rc = snd_pcm_hw_params(handle, params);   if (rc < 0) {     fprintf(stderr,             "unable to set hw parameters: %s\n",             snd_strerror(rc));     exit(1);   } printf( "The Dsp init is atlas ok!\n"); return 0; } static int Uninit_dsp() {    //fclose(fdout);    snd_pcm_drain(handle);    snd_pcm_close(handle);    printf("play end \n"); } /*  * This is the input callback. The purpose of this callback is to (re)fill  * the stream buffer which is to be decoded. In this example, an entire file  * has been mapped into memory, so we just call mad_stream_buffer() with the  * address and length of the mapping. When this callback is called a second  * time, we are finished decoding.  */ static enum mad_flow input(void *data,    struct mad_stream *stream) {   struct buffer *buffer = data;   if (!buffer->length)     return MAD_FLOW_STOP;   mad_stream_buffer(stream, buffer->start, buffer->length);   buffer->length = 0; printf("1111");   return MAD_FLOW_CONTINUE; } /*  * The following utility routine performs simple rounding, clipping, and  * scaling of MAD's high-resolution samples down to 16 bits. It does not  * perform any dithering or noise shaping, which would be recommended to  * obtain any exceptional audio quality. It is therefore not recommended to  * use this routine if high-quality output is desired.  */ static inline signed int scale(mad_fixed_t sample) {   /* round */   sample += (1L << (MAD_F_FRACBITS - 16));   /* clip */   if (sample >= MAD_F_ONE)     sample = MAD_F_ONE - 1;   else if (sample < -MAD_F_ONE)     sample = -MAD_F_ONE;   /* quantize */   return sample >> (MAD_F_FRACBITS + 1 - 16); } static int Get_file_length(char *PATH) {        FILE *fp;      fp=fopen(PATH,"r");     if(!fp)    {    printf("sorry,The file open is faild!\n");    }    else     {     printf("The file open is sucessed!\n");    }    fseek(fp, 0L,SEEK_END);    return (ftell(fp)); } /*  * This is the output callback function. It is called after each frame of  * MPEG audio data has been completely decoded. The purpose of this callback  * is to output (or play) the decoded PCM audio.  */ static 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;   static FILE *fdout;   char buf[1];   /* pcm->samplerate contains the sampling frequency */  fdout= fopen("mypcm.pcm","ab+");   if(!fdout) {  printf("open is failed\n"); }   else printf("out open is ok\n");   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++);     buf[0]=(sample >> 0) & 0xff;     printf("%d\t",buf[0]);     fwrite(buf,1,1,fdout);     buf[0]=(sample >> 8) & 0xff;   printf("%d\t",buf[0]);     fwrite(buf,1,1,fdout);     if (nchannels == 2) {      sample = scale(*right_ch++);      buf[0]=(sample >> 0) & 0xff; fwrite(buf,1,1,fdout);      buf[0]=(sample >> 8) & 0xff; fwrite(buf,1,1,fdout);     }   } fclose(fdout);   return MAD_FLOW_CONTINUE; } static enum mad_flow outputplay(void *data,     struct mad_header const *header,     struct mad_pcm *pcm) {   unsigned int nchannels;   long int nsamples,samplerate;   mad_fixed_t const *left_ch, *right_ch;    static int i=0;   char buf[1];   static char buffer[1024*2*2];   /* pcm->samplerate contains the sampling frequency */   nchannels = pcm->channels;   nsamples  = pcm->length;/* 这个不是采样位,而一帧的数据长度12*3(采样)*32(子带)=1152*/   left_ch   = pcm->samples[0];   right_ch  = pcm->samples[1];   samplerate=pcm->samplerate;   if(!flag) {   printf("channels=%d, samples2=%ld,flag=%d\n", nchannels,samplerate,flag); printf("init dsp is begin\n");   init_dsp(samplerate,nchannels);   memset(buffer,0,sizeof(buffer));    flag++; } #if 1   while (nsamples--) {     signed int sample;     /* output sample(s) in 16-bit signed little-endian PCM */     sample = scale(*left_ch++);     buf[0]=(sample >> 0) & 0xff;     memcpy(buffer+i,buf,1);     i++;    // printf("i=%d,%d,%d\t",i,buf[i-1],buf[0]);     buf[0]=(sample >> 8) & 0xff;   memcpy(buffer+i,buf,1);   i++;     if (nchannels == 2) {      sample = scale(*right_ch++);      buf[0]=(sample >> 0) & 0xff;  memcpy(buffer+i,buf,1);             i++;      buf[0]=(sample >> 8) & 0xff; memcpy(buffer+i,buf,1);           i++;     } if(i==frames*2*nchannels) { i=0; snd_pcm_writei(handle, buffer, frames); }   }   #endif   //snd_pcm_writei(handle, buffer, frames);   return MAD_FLOW_CONTINUE; } /*  * This is the error callback function. It is called whenever a decoding  * error occurs. The error is indicated by stream->error; the list of  * possible MAD_ERROR_* errors can be found in the mad.h (or stream.h)  * header file.  */ static enum mad_flow error(void *data,    struct mad_stream *stream,    struct mad_frame *frame) {   struct buffer *buffer = data;   fprintf(stderr, "decoding error 0x%04x (%s) at byte offset %u\n",  stream->error, mad_stream_errorstr(stream),  stream->this_frame - buffer->start);     Uninit_dsp();   /* return MAD_FLOW_BREAK here to stop decoding (and propagate an error) */   return MAD_FLOW_CONTINUE; } /*  * This is the function called by main() above to perform all the decoding.  * It instantiates a decoder object and configures it with the input,  * output, and error callback functions above. A single call to  * mad_decoder_run() continues until a callback function returns  * MAD_FLOW_STOP (to stop decoding) or MAD_FLOW_BREAK (to stop decoding and  * signal an error).  */ static int decode(unsigned char const *start, unsigned long length) {   struct buffer buffer;   struct mad_decoder decoder;   int result;   /* initialize our private message structure */   buffer.start  = start;   buffer.length = length;   /* configure input, output, and error functions */   mad_decoder_init(&decoder, &buffer,   input, 0 /* header */, 0 /* filter */, outputplay,   error, 0 /* message */);   /* start decoding */   result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);   /* release the decoder */   mad_decoder_finish(&decoder);   return result;

}

以上是基于alas音频驱动的mp3播放器。这里要注意alas送数据是以帧为单位送数据。而oss是以字节为单位,所以先要攒包到frame,再送数据。snd_pcm_writei(handle, buffer, frames); 要注意frames和字节的换算关系:size=frame*(每个采样率所占字节数)*声道数。同时frames不能太小,太小会解码器数据不够f而下溢出。frames只是32。本代码为1M,为的防止概率性同步不上问题

注意alsa架构要链接到alsa库,注意修改makefile编译选项。

CFLAGS = -Wall -march=i486 -g -O  -fforce-addr -fthread-jumps -fcse-follow-jumps -fcse-skip-blocks -fexpensive-optimizations -fregmove -fschedule-insns2 -fstrength-reduce -I/usr/include/alsa -lasound

编译命令:sudo make minimad

即可

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2014-02-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
libmad学习进阶3-----基于oss音频驱动架构的一个mp3播放器
以上就是通过libmad将mp3先解码成pcm,然后将pcm直接扔到/ dev/dsp音频设备中,但dsp音频设备属于oss架构,已经逐渐被alsa驱动取代,后续会介绍基于alsa驱动架构的mp3播放器
用户4148957
2022/06/14
7120
libmad学习进阶2----利用libmad将mp3转码成pcm
# include <stdio.h> # include <unistd.h> # include <sys/stat.h> # include <sys/mman.h> # include "mad.h" #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<stdlib.h> /* * This is perhaps the simplest example use of the MAD high-level API. * Standard input is mapped into memory via mmap(), then the high-level API * is invoked with three callbacks: input, output, and error. The output * callback converts MAD's high-resolution PCM samples to 16 bits, then * writes them to standard output in little-endian, stereo-interleaved * format. */ #define printf static Get_file_length(char *PATH); static int decode(unsigned char const *, unsigned long); int main(int argc, char *argv[]) { printf("The main is start!\n"); struct stat stat; void *fdm; int fd; //char buffer1[80000]; printf("###The input file is %s ! the arc=%d###\n",argv[1],argc); if (argc == 1) { printf("The argc is wrong!\n"); return 1; } #if 0 if (fstat(STDIN_FILENO, &stat) == -1 || stat.st_size == 0) return 2; #endif fd =open(argv[1],O_RDWR); if(-1==fd) { printf("sorry,The file open is faild!\n"); } else { printf("The file open is sucessed!\n"); } //read(fd,buffer1,sizeof(buffer1)); //printf("%s", buffer1); stat.st_size = Get_file_length(argv[1]); printf("The file size is %d\n",stat.st_size ); printf("The Map is begin!\n"); fdm = mmap(0, stat.st_size, PROT_READ, MAP_SHARED, fd, 0); if (fdm == MAP_FAILED) { printf("mmap is failed\n"); return 3; } decode(fdm, stat.st_size); if (munmap(fdm, stat.st_size) == -1) return 4; return 0; } /* * This is a private message structure. A generic pointer to this structure * is passed to each of the callback functions. Put here any data you need * to access from within the callbacks. */ struct buffer { unsigned char const *start; unsigned long length; }; /* * This is the input callback. The purpose of this callback is to
用户4148957
2022/06/14
7070
让终端支持播放mp3,移植mp3解码库libmad和madplay到嵌入式linux
MAD (libmad)是一个开源的高精度 MPEG 音频解码库,支持 MPEG-1(Layer I, Layer II 和 LayerIII(也就是 MP3)。LIBMAD 提供 24 -bit 的 PCM 输出,完全是定点计算,非常适合没有浮点支持的平台上使用。使用 libmad 提供的一系列 API,就可以非常简单地实现 MP3 数据解码工作。
杨永贞
2020/08/04
2.8K0
Linux下使用ffmpeg播放mp3/aac/wav文件的音乐播放器应用
使用ffmpeg实现一个播放器?是不是没什么新意,不过一直使用ffmpeg程序,还没有用ffmpeg代码接口实现播放器,并且还需要使用linux的alsa接口播放出声音,所以做出来还是觉得有点意思;
呱牛笔记
2023/05/02
3.6K0
Linux下使用ffmpeg播放mp3/aac/wav文件的音乐播放器应用
基于alsa驱动架构的pcm播放
/*modify by hfl 2014-2-16*/ /* Use the newer ALSA API */ #define ALSA_PCM_NEW_HW_PARAMS_API #include <alsa/asoundlib.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(int argc, char *argv[]) {   long loops;   int rc;   int size;   snd_pcm_t *handle;   snd_pcm_hw_params_t *params;   unsigned int val;   int dir;   snd_pcm_uframes_t frames;   printf("222133\n");  char buffer[20*2];/*size=frame*channles*byte persaple*/  int fd,i; if (argc != 2) { fprintf (stderr, "usage: %s <filename>!\n", argv[0]); exit ( -1 ) ; } if ( ( fd = open (argv[1],O_RDONLY))<0) { fprintf ( stderr, " Can't open sound file!\n"); exit (-1 ); }   /* Open PCM device for playback. */   rc = snd_pcm_open(&handle, "default",                     SND_PCM_STREAM_PLAYBACK, 0);   if (rc < 0) {     fprintf(stderr,             "unable to open pcm device: %s\n",             snd_strerror(rc));     exit(1);   }   /* Allocate a hardware parameters object. */   snd_pcm_hw_params_alloca(&params);   /* Fill it in with default values. */   snd_pcm_hw_params_any(handle, params);   /* Set the desired hardware parameters. */   /* Interleaved mode */   snd_pcm_hw_params_set_access(handle, params,                       SND_PCM_ACCESS_RW_INTERLEAVED);   /* Signed 16-bit little-endian format */   snd_pcm_hw_params_set_format(handle, params,                               SND_PCM_FORMAT_S16_LE);   /* Two channels (stereo) */   snd_pcm_hw_params_set_channels(handle, params, 1);   /* 44100 bits/second sampling rate (CD quality) */   val = 16000;   snd_pcm_hw_params_set_rate_near(handle, params,                                   &val, &dir);   /* Set period size to 32 frames. */   frames =20;/*一次送人的帧太少,会下溢冲(至少15帧)*/  // snd_pcm_hw_params_set_period_size_near(handle,  params, &frames, &dir);   /* Write the parameters to the driver */   rc = snd_pc
用户4148957
2022/06/14
1K0
FFMPEG音视频开发: Linux下采集音频(alsa-lib库)与视频(V4L2框架)实时同步编码保存为MP4文件(视频录制)
参考这篇文章: https://blog.csdn.net/xiaolong1126626497/article/details/104919095
DS小龙哥
2022/01/12
2.3K0
FFMPEG音视频开发:  Linux下采集音频(alsa-lib库)与视频(V4L2框架)实时同步编码保存为MP4文件(视频录制)
Linux音频驱动-PCM设备
pcm(Pulse-code modulation)脉冲编码调制,是将模拟信号转化为数字信号的一种方法。声音的转化的过程为,先对连续的模拟信号按照固定频率周期性采样,将采样到的数据按照一定的精度进行量化,量化后的信号和采样后的信号差值叫做量化误差,将量化后的数据进行最后的编码存储,最终模拟信号变化为数字信号。
DragonKingZhu
2020/03/24
9.2K0
Linux音频驱动-PCM设备
Linux音频采集和在国产化平台中遇到的坑(一)
虽然都是linux,芯片也是基于同样的架构,同样的指令集,但是考虑到芯片的实现毕竟是不同的,于是所有涉及到硬件交互的软件部分,也会有所差异,最终会导致了有些应用层面的接口,不能按照普通linux的通常用法去使用。
hbstream
2023/01/31
1.9K0
[ 音频篇 ] 29 - 调试智能音箱中音频通路的回采(Ref信号)
项目基于BCM6755平台为基础,通过一系列的语音算法完成实现语音交互场景。这次遇到的问题主要是AEC效果差,如上图所示,设备播放音乐的场景,会出现唤醒困难的想象。实际的抓取录音数据发现录音和回采之间的数据延迟高达100ms,远远超过算法要求<30ms的要求。接下来需要定位延迟的问题。
程序手艺人
2020/11/03
3.5K0
嵌入式Linux下音频开发: alsa-lib实现声音数据捕获保存与播放
项目主页下载地址:https://www.alsa-project.org/wiki/Main_Page
DS小龙哥
2022/01/12
6.3K0
嵌入式Linux下音频开发:  alsa-lib实现声音数据捕获保存与播放
Linux下音频开发: 读取声卡PCM数据保存到文件(alsa-lib库)
如果是在其他发行版linux系统上或者需要在嵌入式linux系统上使用alsa-lib库,可以下载alsa-lib源码包,自行编译。
DS小龙哥
2022/01/12
4.5K0
Linux下音频开发: 读取声卡PCM数据保存到文件(alsa-lib库)
alsa声卡分析alsa-utils调用过程(一)-tinyplay
如何分析tinyplay 播放音频和tinymix的过程?需要相应的工具来支持追查; 一、分析tinyplay和tinymix: 1.1 利用strace工具: strace -o tinyplay.log tinyplay 1.wav strace -o tinymixer.log tinymixer "SEC_MI2S_RX Audio Mixer MultiMedia1" 1  利用strace工具获取APP的log,从应用层往下看; 1.2 分析alsa-utils源码: tiny工具源码在andr
233333
2018/03/29
3.1K0
alsa声卡分析alsa-utils调用过程(一)-tinyplay
ALSA的入门介绍
ALSA由许多声卡的声卡驱动程序组成,同时它也提供一个称为libasound的API库。
刘盼
2023/01/05
2.7K0
Linux下音频设备的操作
1 OSS(Open Sound System)是unix平台上一个统一的音频接口。
程序手艺人
2019/02/21
3.6K0
alsa sample rate跟踪 <1>
本计划全部放在一篇中,后来发现太长。 因此截取成四篇,一口气看800多行,确实够烦的!
全栈程序员站长
2022/11/03
7730
基于嵌入式的车载导航定位系统设计
随着汽车工业的飞速发展和智能化技术的不断突破,车载导航系统作为现代汽车不可或缺的一部分,在人们的日常生活中扮演着越来越重要的角色。它不仅能够提供精确的路线导航,还能提供丰富的地理信息和娱乐服务,为驾驶者带来了极大的便利和乐趣。
DS小龙哥
2024/05/24
5980
基于嵌入式的车载导航定位系统设计
Linux音频驱动-ASOC之Machine
在ASOC小节中描述了整个ASOC的架构,其中Machine是ASOC架构中的关键部件,没有Machine部件,单独的Codec和Platform是无法工作的。因此本节则先从Machine部分开始,那应该如何开始呢? 答案当然是从代码入手,先进入ASOC在kernel中的位置: kernel/sound/soc下
DragonKingZhu
2020/03/24
2.5K0
(干货)Ai音箱和Linux音频驱动小谈
采样就是把模拟信号数字化的过程,不仅仅是音频需要采样,所有的模拟信号都需要通过采样转换为可以用0101来表示的数字信号,示意图如下所示:
刘盼
2019/11/20
3.9K0
(干货)Ai音箱和Linux音频驱动小谈
Linux应用开发【第八章】ALSA应用开发
​ 音频信号是一种连续变化的模拟信号,但计算机只能处理和记录二进制的数字信号,由自然音源得到的音频信号必须经过一定的变换,成为数字音频信号之后,才能送到计算机中作进一步的处理。
韦东山
2021/12/15
3.8K0
Linux应用开发【第八章】ALSA应用开发
Linux音频驱动-AOSC之Platform
在ASOC在Platform部分,主要是平台相关的DMA操作和音频管理。大概流程先将音频数据从内存通过DMA方式传输到CPU侧的dai接口,然后通过CPU的dai接口(通过I2S总线)将数据从达到Codec中,数据会在Codec侧会解码的操作,最终输出到耳机/音箱中。依然已下图作为参考:
DragonKingZhu
2020/03/24
2.9K0
Linux音频驱动-AOSC之Platform
推荐阅读
相关推荐
libmad学习进阶3-----基于oss音频驱动架构的一个mp3播放器
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档