一、MP3播放器:
本设计根据libmad库中minimad.c改写成的,保留了原始的英文注释,minimad.c实现了MP3的解码成PCM音频数据,打印到屏幕上。本设计添加了alsa的播放设置函数,以及在解码output的函数中,将输出写入到声卡中,实现了MP3 文件的解码播放。
注意:本设计编译之前需要编译libmad库, 编译时需要连上 -lmad -lasound 的选项。
使用方法为在终端:./mp3-player + mp3 file.
mp3-player.c:

/*
 * libmad - MPEG audio decoder library
 * Copyright (C) 2000-2004 Underbit Technologies, Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: minimad.c,v 1.4 2004/01/23 09:41:32 rob Exp $
 */

# include <stdio.h>
# include <unistd.h>
# include <sys/stat.h>
# include <sys/mman.h>

#include <string.h>
#include<fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <alsa/asoundlib.h>

# include "mad.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.
 */

static int decode(unsigned char const *, unsigned long);
int set_pcm();
snd_pcm_t*             handle=NULL;        //PCI设备句柄
snd_pcm_hw_params_t*   params=NULL;//硬件信息和PCM流配置

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

if (argc != 2)
    {
    printf("Usage: minimad + mp3 file name");
    return 1;
    }
  int fd;
  fd=open(argv[1],O_RDWR);
  if(fd<0)
  {
    perror("open file failed:");
    return 1;
  }    
 
  if (fstat(fd, &stat) == -1 ||stat.st_size == 0)
  {
    printf("fstat failed:\n");
    return 2;
  }
   //printf("stat.st_size=%d\n",stat.st_size);
  
  fdm = mmap(0, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
  if (fdm == MAP_FAILED)
    return 3;

if(set_pcm()!=0)                 //设置pcm 参数
    {
        printf("set_pcm fialed:\n");
        return 1;   
    }
  decode(fdm, stat.st_size);

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

snd_pcm_drain(handle);
    snd_pcm_close(handle);

return 0;
}

int set_pcm()
{
    int    rc;     
    int  dir=0;
    int rate = 44100;;                /* 采样频率 44.1KHz*/
    int format = SND_PCM_FORMAT_S16_LE; /*     量化位数 16      */
    int channels = 2;                 /*     声道数 2           */
    
    rc=snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
        if(rc<0)
        {
                perror("\nopen PCM device failed:");
                exit(1);
        }
    snd_pcm_hw_params_alloca(&params); //分配params结构体
        
    rc=snd_pcm_hw_params_any(handle, params);//初始化params
        if(rc<0)
        {
                perror("\nsnd_pcm_hw_params_any:");
                exit(1);
        }
    rc=snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);                                 //初始化访问权限
        if(rc<0)
        {
                perror("\nsed_pcm_hw_set_access:");
                exit(1);

}
        
    rc=snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);             //设置16位采样精度  
        if(rc<0)
       {
            perror("snd_pcm_hw_params_set_format failed:");
            exit(1);
        } 
        
    rc=snd_pcm_hw_params_set_channels(handle, params, channels);  //设置声道,1表示单声>道,2表示立体声
        if(rc<0)
        {
                perror("\nsnd_pcm_hw_params_set_channels:");
                exit(1);
        }    
        
     rc=snd_pcm_hw_params_set_rate_near(handle, params, &rate, &dir);  //设置>频率
        if(rc<0)
        {
                perror("\nsnd_pcm_hw_params_set_rate_near:");
                exit(1);
        }   
        
         
    rc = snd_pcm_hw_params(handle, params);
        if(rc<0)
        {
        perror("\nsnd_pcm_hw_params: ");
        exit(1);
        } 
   
    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 (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;

printf("this is input\n");
  if (!buffer->length)
    return MAD_FLOW_STOP;

mad_stream_buffer(stream, buffer->start, buffer->length);

buffer->length = 0;

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);
}

/*
 * 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,n;
  mad_fixed_t const *left_ch, *right_ch;

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

nchannels = pcm->channels;
  n=nsamples  = pcm->length;
  left_ch   = pcm->samples[0];
  right_ch  = pcm->samples[1];
  
  unsigned char Output[6912], *OutputPtr;  
  int fmt, wrote, speed, exact_rate, err, dir; 
  
  
//   printf("This is output\n");
   
   
 
   OutputPtr = Output;  
   
   while (nsamples--) 
   {
    signed int sample;

/* output sample(s) in 16-bit signed little-endian PCM */
    
    sample = scale(*left_ch++);
   
    *(OutputPtr++) = sample >> 0;  
    *(OutputPtr++) = sample >> 8;  
    if (nchannels == 2)  
        {  
            sample = scale (*right_ch++);  
            *(OutputPtr++) = sample >> 0;  
            *(OutputPtr++) = sample >> 8;  
        }  
    
  
  }
 
    OutputPtr = Output;  
    snd_pcm_writei (handle, OutputPtr, n);  
    OutputPtr = Output;

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;
  printf("this is mad_flow error\n");
  fprintf(stderr, "decoding error 0x%04x (%s) at byte offset %u\n",
      stream->error, mad_stream_errorstr(stream),
      stream->this_frame - buffer->start);

/* 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 */, output,
           error, 0 /* message */);

/* start decoding */

result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);

/* release the decoder */

mad_decoder_finish(&decoder);

return result;
}

二、WAV播放器:

本设计思路:先打开一个普通wav音频文件,从定义的文件头前面的44个字节中,取出文件头的定义消息,置于一个文件头的结构体中。然后打开alsa音频驱动,从文件头结构体取出采样精度,声道数,采样频率三个重要参数,利用alsa音频驱动的API设置好参数,最后打开wav文件,定位到数据区,把音频数据依次写到音频驱动中去,开始播放,当写入完成后,退出写入的循环。

注意:本设计需要alsa的libasound-dev的库,编译链接时需要连接 —lasound.

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <alsa/asoundlib.h>

struct WAV_HEADER
{
    char rld[4];    //riff 标志符号
    int rLen;   
    char wld[4];    //格式类型(wave)
    char fld[4];    //"fmt"

int fLen;   //sizeof(wave format matex)
    
    short wFormatTag;   //编码格式
    short wChannels;    //声道数
    int   nSamplesPersec ;  //采样频率
    int   nAvgBitsPerSample;//WAVE文件采样大小
    short  wBlockAlign; //块对齐
    short wBitsPerSample;   //WAVE文件采样大小
    
    char dld[4];        //”data“
    int wSampleLength;  //音频数据的大小

} wav_header;

int set_pcm_play(FILE *fp);

int main(int argc,char *argv[])
{

if(argc!=2)
    {
        printf("Usage:wav-player+wav file name\n");
        exit(1);
    }

int nread;
    FILE *fp;
    fp=fopen(argv[1],"rb");
    if(fp==NULL)
    {
        perror("open file failed:\n");
        exit(1);
    }
    
    nread=fread(&wav_header,1,sizeof(wav_header),fp);
    printf("nread=%d\n",nread);
    
    //printf("RIFF 标志%s\n",wav_header.rld);
    printf("文件大小rLen:%d\n",wav_header.rLen);
    //printf("wld=%s\n",wav_header.wld);
    //printf("fld=%s\n",wav_header.fld);
    
   // printf("fLen=%d\n",wav_header.fLen);
    
    //printf("wFormatTag=%d\n",wav_header.wFormatTag);
    printf("声道数:%d\n",wav_header.wChannels);
    printf("采样频率:%d\n",wav_header.nSamplesPersec);
    //printf("nAvgBitsPerSample=%d\n",wav_header.nAvgBitsPerSample);
    //printf("wBlockAlign=%d\n",wav_header.wBlockAlign);
    printf("采样的位数:%d\n",wav_header.wBitsPerSample);
    
   // printf("data=%s\n",wav_header.dld);
    printf("wSampleLength=%d\n",wav_header.wSampleLength);
    
    
    
    
    
    set_pcm_play(fp);
    return 0;
}

int set_pcm_play(FILE *fp)
{
        int    rc;
        int    ret;
        int    size;
        snd_pcm_t*       handle;        //PCI设备句柄
        snd_pcm_hw_params_t*      params;//硬件信息和PCM流配置
        unsigned int       val;
        int                dir=0;
        snd_pcm_uframes_t  frames;
        char   *buffer;
        int channels=wav_header.wChannels;
        int frequency=wav_header.nSamplesPersec;
        int bit=wav_header.wBitsPerSample;
        int datablock=wav_header.wBlockAlign;
        unsigned char ch[100];  //用来存储wav文件的头信息
    
    
        
        rc=snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
        if(rc<0)
        {
                perror("\nopen PCM device failed:");
                exit(1);
        }

snd_pcm_hw_params_alloca(&params); //分配params结构体
        if(rc<0)
        {
                perror("\nsnd_pcm_hw_params_alloca:");
                exit(1);
        }
         rc=snd_pcm_hw_params_any(handle, params);//初始化params
        if(rc<0)
        {
                perror("\nsnd_pcm_hw_params_any:");
                exit(1);
        }
        rc=snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);                                 //初始化访问权限
        if(rc<0)
        {
                perror("\nsed_pcm_hw_set_access:");
                exit(1);

}

//采样位数
        switch(bit/8)
        {
        case 1:snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_U8);
                break ;
        case 2:snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);
                break ;
        case 3:snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S24_LE);
                break ;

}
        rc=snd_pcm_hw_params_set_channels(handle, params, channels);  //设置声道,1表示单声>道,2表示立体声
        if(rc<0)
        {
                perror("\nsnd_pcm_hw_params_set_channels:");
                exit(1);
        }
        val = frequency;
        rc=snd_pcm_hw_params_set_rate_near(handle, params, &val, &dir);  //设置>频率
        if(rc<0)
        {
                perror("\nsnd_pcm_hw_params_set_rate_near:");
                exit(1);
        }

rc = snd_pcm_hw_params(handle, params);
        if(rc<0)
        {
        perror("\nsnd_pcm_hw_params: ");
        exit(1);
        }

rc=snd_pcm_hw_params_get_period_size(params, &frames, &dir);  /*获取周期
长度*/
        if(rc<0)
        {
                perror("\nsnd_pcm_hw_params_get_period_size:");
                exit(1);
        }

size = frames * datablock;   /*4 代表数据快长度*/

buffer =(char*)malloc(size);
    fseek(fp,58,SEEK_SET);  //定位歌曲到数据区

while (1)
        {
                memset(buffer,0,sizeof(buffer));
                ret = fread(buffer, 1, size, fp);
                if(ret == 0)
                {
                        printf("歌曲写入结束\n");
                        break;
                }
                 else if (ret != size)
                {
                 }
                // 写音频数据到PCM设备  
        while(ret = snd_pcm_writei(handle, buffer, frames)<0)
           {
                 usleep(2000);  
                 if (ret == -EPIPE)
                {
                  /* EPIPE means underrun */
                  fprintf(stderr, "underrun occurred\n");
                  //完成硬件参数设置,使设备准备好  
                  snd_pcm_prepare(handle);
                 }
                 else if (ret < 0)
                 {
                          fprintf(stderr,
                      "error from writei: %s\n",
                      snd_strerror(ret));
                 }
            }

}

snd_pcm_drain(handle);
        snd_pcm_close(handle);
        free(buffer);
        return 0;
}

linux下音乐播放器wav和mp3相关推荐

  1. linux播放器安装程序,Linux下音乐播放器Audacious 3.10下载与安装

    一款Linux下的音乐播放器Audacious 3.10正式发布下载了,它带来了新的功能和一些重要改进,尽管Audacious 4.0(具有功能齐全的 Qt UI)还没有开发出来,但他们也没有闲着,代 ...

  2. linux一键电影网站脚本,Linux下HTML5播放器一键生成脚本

    原创内容,转载请注明出处: https://www.myzhenai.com.cn/post/2394.html https://www.myzhenai.com/thread-17969-1-1.h ...

  3. linux 中文 音乐播放器,linux下的常见音乐播放器

    xmms 老牌的音乐播放器,模仿Windows下*的播放器Winamp,其强大的功能不输于Winamp,具有极强的可扩展性,支持mp3.ogg.wav等格式播放,添加插件后还可以播放AAC.wma等格 ...

  4. linux qt4 音乐播放器,Ubuntu 14.04下安装音乐播放器 Clementine 1.2.3

    Clementine 是一款非常不错的自由开源音乐播放器,支持很多国外的云空间,比如box.com.Clementine使用qt4编写,灵感来自Amarok 1.4.Clementine还是一款跨平台 ...

  5. mp3 添加封面 linux,Qmmp音乐播放器1.2.0发布! Ubuntu中安装方法

    Qmmp是一款基于Qt的音乐播放器,它具有winamp或xmms接口,目前已经发布了1.2.0版本(Qt4版本为0.11.0),并增加了许多新功能,改进以及一些错误修复. Qmmp 1.2.0(0.1 ...

  6. linux终端音乐播放器,Linux终端音乐播放器cmus攻略: 操作歌单

    cmus是一款开源的终端音乐播放器.它小巧快速,而又功能强大.cmus支持Ogg/Vorbis.MP3.FLAC.Musepack.WavPack.WMA.WAV.AAC.MP4等格式,包含Gaple ...

  7. 基于嵌入式linux的音乐播放器设计,基于嵌入式Linux的多媒体音乐播放器的设计与实现...

    中图分类号:TP316.5 文献标识码:A 文章编号:1009-2552(2009)06-0102-03 基于嵌入式Linux的多媒体音乐播放器的设计与实现 王 奇 (黑龙江八一农垦大学信息技术学院, ...

  8. Linux项目:音乐播放器

    文章目录 1.项目介绍 2.前端代码 1.httplib快速搭建一个http服务器 2.B/S双方的数据交互选择JSON数据格式,http请求和响应的正文中采用jsoncpp开源库 3.前段的js代码 ...

  9. linux下音乐播放软件

    虽然说大家用linux一般是工作,但工作累了总要休息吧,听听音乐还是不错的. linux 下有很多免费的好用的音乐播放客户端,我用的系统是Ubuntu12.04LTS ,默认的播放器是Rhythmbo ...

最新文章

  1. matepad和鸿蒙,爆料称华为MatePad 2系列平板有三个版本:预装鸿蒙OS
  2. ASP.NET中的事务处理和异常处理
  3. Java类加载机制详解【java面试题】
  4. day11 - 15(装饰器、生成器、迭代器、内置函数、推导式)
  5. activity中fragment 返回键不退出_优雅地处理加载中(loading),重试(retry)和无数据(empty)等...
  6. 【数据库】Ubuntu18.04安装MySQL详解
  7. 计算机科学与软件工程的区别
  8. 内河港口首次实现区块链无纸化进口放货
  9. pb预览状态下的pagecount_QuickLook高效文件预览神器,方便到令你意想不到
  10. Flask框架(一)
  11. 【论文写作】SSH在线订餐系统如何写软件测试章节
  12. 哪些SQL语句会引起全表扫描
  13. 图解排序算法之「冒泡排序」(详细解析)
  14. 应用VB语言程序生成十个随机数
  15. 专访 | 刘嘉松:开源,互惠且共赢
  16. 【推荐系统】今日头条推荐算法原理全文详解
  17. spyder设置显示编码_OBS编码器选择“硬件(NVENC)”导致无法录屏解决办法
  18. 【Linux】新唐NUC977系统编译及烧写流程
  19. python迅雷自动下载_Python3.x+迅雷x 自动下载高分电影的实现方法
  20. 生产环境容器落地最佳实践 - JFrog 内部 K8s 落地旅程

热门文章

  1. day19三大神器和csv文件
  2. Python三大神器和csv文件操作
  3. 松柏先生与阿里巴巴副总裁、天猫总裁一同出席2018电商发展创新峰会
  4. ZOJ3775 ?(_o)!
  5. Linux查询安装的软件所在目录
  6. BeetlSql简介及举例
  7. RegisterHotKey设置系统级热键《转》
  8. 偷偷学习qt 样式,然后写出惊艳所有人的界面
  9. xcode8注释快捷键
  10. 【深度学习】如何选择适合深度学习的GPU?