linux 基于alsa 使用libmad 解码库实现MP3文件的播放

MyMinimad ── Linux下用libmad写的mp3解码播放程序(二) 装上fedora12后发现没有/dev/dsp了,所以用ALSA把这个程序重写了下。 程序说明:其实本来应该是在output函数中设置采样率和声道数的,但有莫名奇妙的问题。所以定了个一般化的#define SAMPLE_RATE 44100#define CHANNELS 2#define PCM_DEVICE "plughw:0,0"即:mp3的采样率为44100Hz 阅读详情

本设计根据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;
}

转自:http://blog.chinaunix.net/uid-27106528-id-3334746.html

Linux音频处理实战:从MP3解码到ALSA播放的完整流程解析 本文详细解析了Linux环境下从MP3解码到ALSA播放的完整音频处理流程。涵盖MP3文件结构解析、PCM信号处理技巧以及ALSA播放配置优化,提供实用的代码示例和调试建议,帮助开发者高效实现音频处理工具链搭建。特别针对ALSA播放中的常见问题给出解决方案。 阅读详情

相关推荐

告别FFmpeg臃肿:在嵌入式Linux上用libmad(MAD)实现MP3流式解码的完整流程

本文详细介绍了在嵌入式Linux环境下使用轻量级开源库libmad实现MP3流式解码的完整方案。通过双缓冲区设计、动态帧同步和内存池管理等优化技术,在树莓派等资源受限设备上实现高效音频解码,内存占用控制在1KB以内,同时保持CD级音质。相比传统FFmpeg方案,libmad在嵌入式场景中展现出显著优势。

weixin_33675507的博客 457

libmad+alsa 实现arm下mp3播放

libmad+alsa 实现arm下mp3播放 2015-10-10 18:42:55 原文libmad是一个开源的mp3解码库,轻便高效,mplayer也是用这个库来解码mp3的。ALSA(Advanced Linux Sound Architecture)是Linux中提供声音设备驱动的内核组件,用来代替原来的开放声音系统(Open Sound System,OSSv3)。除了声音设备驱动,A

蔡松豆的博客 2254

基于alsa和libmad嵌入式mp3播放器

可移植ok6410 的mp3播放器,基于alsa和libmad库,内含编译好的库和播放器以及源代码,解压后可直接运行,和以移植好的mplayer官方播放器(可快进 暂停 时间轴 音量控制等)

【转】Alsa音频编程【精华】

一、前序 这里了解一下各个参数的含义以及一些基本概念。 声音是连续模拟量,计算机将它离散化之后用数字表示,就有了以下几个名词术语。 样本长度(sample):样本是记录音频数据最基本的单位,计算机对每个通道采样量化时数字比特位数,常见的有8位和16位。 通道数(channel):该参数为1表示单声道,2则是立体声。 帧(frame):帧记录了一个声音单元,其长度为样本长度与通道数的乘积,...

weixin_30467087的博客 799

alsa本地录音并播放程序

解压后,make生成可执行文件,执行即可,需要提前安装alsa的库文件

libmad+libao解码播放音乐

改实例实现了在mt7628平台编译并使用alsa播放mp3音频,并解决在mips平台编译libmad产生的编译问题

ALSA播放MP3

1、MP3文件转码为WAV格式(解码为pcm); 2、通过ALSA接口读取pcm播放; ALSA接口使用步骤: 1、打开声卡; 2、分配声卡params结构体空间; 3、初始化和设置params结构体; 4、将该params设置到声卡; 5、设置声卡的声道、频率; 6、读取pcm文件到设备; //alsa.c 编写者未知,纯属引用 #include<stdio....

吸喵高手的小窝 1472

【深度学习3】ubuntu22.04从零开始搭建深度学习环境

ubuntu22.04从零开始搭建深度学习开发环境

weixin_43387635的博客 1万+

alsa数据编码mp3格式

在linux系统中,有的系统没有dsp 设备文件,所以只能使用alsa提供的接口来读取声音设备。alsa 又许多的声卡和声卡驱动组成,它可以直接读取声卡采集到的数据。如同摄像头数据一般,采集到的原始数据都是都是非常大的,不利于我们正常存储和使用,所以出现了很多的压缩方法。本文采用的是国内使用最广的mp3压缩方式。先上代码:/*================================...

Biao 1558

基于MATLAB/Simulink与WSL2的ROS2实时联合仿真实践

本文详细介绍了基于MATLAB/Simulink与WSL2的ROS2实时联合仿真实践。通过环境配置、PX4仿真环境搭建、自定义消息生成、Simulink通信实现及实时优化等步骤,提供了完整的无人机位置控制案例,帮助开发者实现高精度的实时联合仿真。

red88的博客 202

Unity海洋渲染实战:Ceto Ocean System核心原理与高级应用指南

实时水面渲染是计算机图形学中的重要课题,涉及波浪模拟、光照交互和着色器编程等核心技术。其原理通常基于物理模型,如使用Gerstner波模拟规则海浪,或通过快速傅里叶变换(FFT)处理频谱数据生成随机海面。这些技术的价值在于能以可控的性能开销,在游戏中实现具有体积感、反射和折射效果的真实水体。在开放世界、海战模拟等应用场景中,专业的海洋系统如Ceto Ocean System,通过模块化架构整合了波浪生成、动态网格和渲染管线,为开发者提供了完整的解决方案。本文深入探讨了其双引擎波浪系统和多层渲染结构,并分享了

weixin_29002595的博客 279

解决minincom:cannot open /dev/modem 问题最根本的办法,应该是全网唯一

启动minicom的时候,出现错误提示:minincom: cannot open /dev/modem sudo minicom -d ttyUSB0

cakoo的博客 1万+

华为开发岗暑期实习笔试(2025年4月16日)

第一题怀疑测试样例不完整,贪心法不应该能够解决该题。第二题使用0-1BFS解决单源最短路径的问题,往往搭配双端队列实现。第三题是运用动态规划解决最大不重叠子区间个数的问题,难点在于满足3重判断规则,所需数据结构及相关操作较多。

csy031117的博客 3661

linux下使用libmad库实现mp3文件的解码、播放

据说这个更新到2004年2月的libmad是一种高品质的MPEG音频解码器,支持24-bit输出,优点多多。 对其的详细介绍请参考主页:http://www.underbit.com/products/mad/ 准备工作 x86_64平台的编译可直接运行configure,arm下 libmad: ./configure --host=arm-xxx(arm-xxx为交叉编译工具的前缀) ...

知其可为而不为 1万+

菜鸟-需求预测与分仓规划

通过修改模型的损失函数对问题进行求解,比其它单模型的效果好很多。

永不理解_fdu的博客 4881

视频理解与处理——OpenClaw视频能力深度解析(2026视频版)

本文介绍了OpenClaw视频理解与处理的核心技术,重点分析了视频预处理流程。通过VideoProcessor类实现视频加载、帧采样、尺寸调整和归一化等基础处理功能,支持本地和在线视频源处理,为后续视频分析任务提供标准化输入。预处理模块采用均匀采样和标准化方法优化视频数据,确保动作识别、场景分析等高级应用的准确性,展现了OpenClaw强大的视频处理能力。

一键难忘的博客 464

在 Fedora 5 Linux 下实现了一个基于 libmad 的 MP3 流媒体播放器

 基于 libmad 的简单 MP3 流媒体播放器的实现,转自十八摸developerworks2007-04-17 16:11李 素科 (lisuke@infosec.pku.edu.cn), 讲师, 北京大学软件学院2007 年 2 月 02 日1.介绍本文在 Fedora 5 Linux 下实现了一个基于 libmad 的 MP3 流媒体播放器。此流媒体播放器可以

老向的专栏 1657

26、特洛伊木马:威胁与防范

本文详细介绍了多种常见的特洛伊木马,包括RegForm、ProMail和远程访问特洛伊木马(RATs),并分析了其工作原理与危害。重点讲解了著名RATs如Back Orifice、SubSeven和The Thing的技术特点,揭示了黑客编写特洛伊木马的常用语言与方法。同时,提供了有效的防范策略,如谨慎获取软件、使用回滚程序、杀毒软件、防火墙及反特洛伊木马程序,并通过流程图展示了防御机制。旨在帮助用户识别威胁并加强系统安全防护。

e3f4g5的博客 88

基于libmad 的简单MP3流媒体播放器的实现

1.介绍    本文在 Fedora 5 Linux 下实现了一个基于 libmad 的 MP3 流媒体播放器。此流媒体播放器可以播放基于 HTTP 1.1 协议传输的 MP3 流媒体数据。    基本原理是:从 HTTP 服务器获得 MP3 媒体信息,然后通过网络传输把 MP3 数据以数据流的形式接收到 MP3流媒体播放器客户端,由客户端通过 libmad 解码 MP3 数据流,得

shenbin1430的专栏 1471

AI:270-基于ASFF改进YOLOv8检测头的多尺度特征融合方法详解与实战

ASFF是一种基于自适应特征融合的策略,能够动态调整不同尺度特征的融合权重,适应场景中不同大小的目标。传统的YOLOv8检测头使用固定的特征融合策略,而ASFF则通过引入学习参数,使得网络能够根据输入图像的特征自适应地选择不同尺度特征的重要性。这一策略对于检测小目标或尺度变化大的目标具有显著优势。本文提出了一种改进YOLOv8检测头的新方法,通过引入自适应空间特征融合模块(ASFF),有效提升了多尺度目标检测的性能,特别是在小目标检测任务中的表现。

一键难忘的博客 3911

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

java alsa 编程_MyMinimad ── Linux下用libmad写的mp3解码播放程序(三)

csdn的博客帐号当年那个事件中被盗了,相应的邮箱也被盗了,这次写在这里。/** 本程序是从 minimad 改进而来,如要更详细的说明请参看 minimad.c** Gu Zhou, 2009/12/25, SiChuan University, China** 系统: ubuntu 19.10* 依赖: sudo apt install libmad0-dev libasound2-dev* ...

weixin_34006872的博客 158

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

基于 libmad 的简单 MP3 流媒体播放器的实现

基于 libmad 的简单 MP3 流媒体播放器的实现级别: 中级李 素科 (lisuke@infosec.pku.edu.cn), 讲师, 北京大学软件学院2007 年 2 月 02 日本文在 Fedora 5 Linux 下实现了一个基于 libmad 的 MP3 流媒体播放器。此流媒体播放器可以播放基于 HTTP 1.1 协议传输的 MP3 流媒体数据。1.介绍

Wave的专栏 2934

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

MyMinimad ── Linux下用libmad写的mp3解码播放程序

程序说明:其实本来应该是在output函数中设置采样率和声道数的,但有莫名奇妙的问题。 所以定了个一般化的 #define SAMPLE_RATE 44100 #define CHANNELS 2 #define PCM_DEVICE "plughw:0,0" 即:mp3的采样率为44100Hz,声道数为2(立体声) 源代码: /* * 本程序是从 minimad 改进而来,如

jwzhangjie的专栏 3242
上一篇: pthread 主线程子线程退出关系
下一篇: ifly error code 讯飞离线识别错误码
人生如叶
博客等级 码龄12年 118粉丝 45原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值