音频demo:使用开源项目libmad来将MP3数据解码出PCM数据

1、README

前言

本demo是使用开源项目libmad来将MP3数据解码成PCM(16位有符号小字节序)数据。(环境:x86_64 Ubuntu16.04 64位)

a. 编译使用

libmad的编译:

  • 源码下载地址1:https://sourceforge.net/projects/mad/files/libmad/

  • 源码下载地址2:https://www.linuxfromscratch.org/blfs/view/svn/multimedia/libmad.html

tar xzf libmad-0.15.1b.tar.gz
cd libmad-0.15.1b/
sed -i '/-fforce-mem/d' configure   # 如果不执行这句命令,一些编译器可能会报"gcc: error: unrecognized command line option '-fforce-mem'"错误
./configure --prefix=$PWD/_install --enable-static --disable-shared
make
make install

demo的编译与使用:

$ make clean && make
$ 
$ ./mp32pcm
Usage:./mp32pcm <in MP3 file> <out PCM file>
Examples:./mp32pcm audio/test1_44100_stereo.mp3 out1_44100_16bit_stereo.pcm./mp32pcm audio/test2_22050_stereo.mp3 out2_22050_16bit_stereo.pcm./mp32pcm audio/test3_22050_mono.mp3   out3_22050_16bit_mono.pcm./mp32pcm audio/test4_8000_mono.mp3    out4_8000_16bit_mono.pcm
b. 参考文章
  • libmad linux交叉编译移植_SongYuLong的博客的博客-CSDN博客_libmad 交叉编译l
  • 基于Libmad的流媒体解码播放Demo - 简书
  • libmad-0.15.1b/minimad.c(以放到本demo中的docs/reference_code/目录。)
c. demo目录架构
$ tree
.
├── audio
│   ├── out1_44100_16bit_stereo.pcm
│   ├── out2_22050_16bit_stereo.pcm
│   ├── out3_22050_16bit_mono.pcm
│   ├── out4_8000_16bit_mono.pcm
│   ├── test1_44100_stereo.mp3
│   ├── test2_22050_stereo.mp3
│   ├── test3_22050_mono.mp3
│   └── test4_8000_mono.mp3
├── docs
│   ├── libmad linux交叉编译移植_SongYuLong的博客的博客-CSDN博客_libmad 交叉编译.mhtml
│   ├── reference_code
│   │   └── minimad.c
│   └── 基于Libmad的流媒体解码播放Demo - 简书.mhtml
├── include
│   └── mad.h
├── lib
│   └── libmad.a
├── main.c
├── Makefile
└── README.md

2、主要代码片段

main.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 <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <stdlib.h># include "mad.h"#ifdef ENABLE_DEBUG#define DEBUG(fmt, args...)     printf(fmt, ##args)
#else#define DEBUG(fmt, args...)
#endif/** 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 *inMp3Data;unsigned long inMp3DataLen;unsigned char *outPcmData;unsigned long outPcmDataLen;
};/** 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 mp3_decode_body(struct buffer *);int main(int argc, char *argv[])
{struct stat stat;int fdMp3 = -1;void *vfdMp3 = NULL; /* mmap */FILE *fpPcm = NULL;char *inMp3FileName = NULL;char *outPcmFileName = NULL;struct buffer bufferInfo= {};if (argc != 3){printf("Usage: \n""    %s <in MP3 file> <out PCM file>\n""Examples: \n""    %s audio/test1_44100_stereo.mp3 out1_44100_16bit_stereo.pcm\n""    %s audio/test2_22050_stereo.mp3 out2_22050_16bit_stereo.pcm\n""    %s audio/test3_22050_mono.mp3   out3_22050_16bit_mono.pcm\n""    %s audio/test4_8000_mono.mp3    out4_8000_16bit_mono.pcm\n",argv[0], argv[0], argv[0], argv[0], argv[0]);return -1;}else{inMp3FileName = argv[1];outPcmFileName = argv[2];}/* open MP3 file and map to memory */fdMp3 = open(inMp3FileName, O_RDONLY);if (fdMp3 < 0){perror("open input MP3 file failed");goto exit;}if (fstat(fdMp3/*STDIN_FILENO*/, &stat) == -1 ||stat.st_size == 0)goto exit;printf("decode input MP3 size: %lu\n", stat.st_size);vfdMp3 = mmap(0, stat.st_size, PROT_READ, MAP_SHARED, fdMp3/*STDIN_FILENO*/, 0);if (vfdMp3 == MAP_FAILED){printf("map MP3 file to memory failed!\n");goto exit;}/* fix up our struct, and we will use to decode mp3 data! */bufferInfo.inMp3Data = vfdMp3;bufferInfo.inMp3DataLen = stat.st_size;bufferInfo.outPcmData = malloc(stat.st_size * 15); /* decode out buf size */if (!bufferInfo.outPcmData){printf("alloc memory to decode output PCM failed!\n");goto exit;}bufferInfo.outPcmDataLen = 0; /* init to 0 *//* decode MP3 data with our struct !!!!! */mp3_decode_body(&bufferInfo);/* save the decoded out PCM data */fpPcm = fopen(outPcmFileName, "wb");if (!fpPcm){printf("open output PCM file failed!\n");goto exit;}else{printf("decode output total PCM size: %lu\n", bufferInfo.outPcmDataLen);fwrite(bufferInfo.outPcmData, 1, bufferInfo.outPcmDataLen, fpPcm);fflush(fpPcm);fclose(fpPcm);}exit:if (munmap(vfdMp3, stat.st_size) == -1)return -1;if (fdMp3)close(fdMp3);if (bufferInfo.outPcmData)free(bufferInfo.outPcmData);return 0;
}/** 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 mp3_decode_input(void *data,struct mad_stream *stream)
{struct buffer *buffer = data;if (!buffer->inMp3DataLen)return MAD_FLOW_STOP;DEBUG("[%s: %d] decode input size: %lu\n", __FUNCTION__, __LINE__, buffer->inMp3DataLen);mad_stream_buffer(stream, buffer->inMp3Data, buffer->inMp3DataLen);buffer->inMp3DataLen = 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 mp3_decode_output(void *data,struct mad_header const *header,struct mad_pcm *pcm)
{struct buffer *buffer = data;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];DEBUG("[%s: %d] decode ouput size: %d\n", __FUNCTION__, __LINE__, nsamples*2*nchannels/* print as 16bit */);while (nsamples--) {signed int sample;/* output sample(s) in 16-bit signed little-endian PCM */sample = scale(*left_ch++);#if 0putchar((sample >> 0) & 0xff);putchar((sample >> 8) & 0xff);#elsebuffer->outPcmData[buffer->outPcmDataLen++] = (sample >> 0) & 0xff;buffer->outPcmData[buffer->outPcmDataLen++] = (sample >> 8) & 0xff;#endifif (nchannels == 2) {sample = scale(*right_ch++);#if 0putchar((sample >> 0) & 0xff);putchar((sample >> 8) & 0xff);#elsebuffer->outPcmData[buffer->outPcmDataLen++] = (sample >> 0) & 0xff;buffer->outPcmData[buffer->outPcmDataLen++] = (sample >> 8) & 0xff;#endif}}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 mp3_decode_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 %lu\n",stream->error, mad_stream_errorstr(stream),stream->this_frame - buffer->inMp3Data);/* 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 mp3_decode_body(struct buffer *bufferInfo)
{//struct buffer buffer;struct mad_decoder decoder;int result;#if 0/* initialize our private message structure */buffer.start  = start;buffer.length = length;#endif/* configure input, output, and error functions */mad_decoder_init(&decoder, bufferInfo,mp3_decode_input, 0 /* header */, 0 /* filter */, mp3_decode_output,mp3_decode_error, 0 /* message */);/* start decoding */result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);/* release the decoder */mad_decoder_finish(&decoder);return result;
}

3、demo下载地址(任选一个)

  • https://download.csdn.net/download/weixin_44498318/89525488

  • https://gitee.com/linriming/audio_mp32pcm_with_libmad.git

  • https://github.com/linriming20/audio_mp32pcm_with_libmad.git

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/371978.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity | Shader基础知识(第十七集:学习Stencil并做出透视效果)

目录 一、前言 二、了解unity预制的材质 三、什么是Stencil 四、UGUI如何使用Stencil&#xff08;无代码&#xff09; 1.Canvas中Image使用Stencil制作透视效果 2.学习Stencil 3.分析透视效果的需求 五、模型如何使用Stencil 1.shader准备 2.渲染顺序 3.Stencil代码语…

CFS三层内网渗透——外网打点(一)

目录 外网打点 先爆破一下看看有没有啥可进攻路径 尝试那个可疑的路径发现是thinkphp这个框架&#xff0c;同时也知道了版本&#xff0c;那就nday打吧 写入php ​编辑写入php成功&#xff0c;简简单单nday拿下​编辑 蚁剑rce尝试链接 打点成功 外网打点 先爆破一下看看有…

前端使用Threejs加载机械臂并控制机械臂跳舞

1. 前言 在我的第一篇博客中,大致讲解了如何使用threejs导入机械臂模型,以及如何让机械臂模型动起来的案例,可以看一下之前的博客前端使用Threejs控制机械臂模型运动 本篇博客主要讲解的是在原来的基础上添加GSAP动画库的应用,可以通过动画,来让机械臂进行指定轨迹位姿的运动…

【鸿蒙学习笔记】页面布局

官方文档&#xff1a;布局概述 常见页面结构图 布局元素的组成 线性布局&#xff08;Row、Column&#xff09; 了解思路即可&#xff0c;更多样例去看官方文档 Entry Component struct PracExample {build() {Column() {Column({ space: 20 }) {Text(space: 20).fontSize(15)…

vue3实现echarts——小demo

版本&#xff1a; 效果&#xff1a; 代码&#xff1a; <template><div class"middle-box"><div class"box-title">检验排名TOP10</div><div class"box-echart" id"chart1" :loading"loading1"&…

conda中创建环境并安装tensorflow1版本

conda中创建环境并安装tensorflow1版本 一、背景二、命令三、验证一下 一、背景 最近需要使用tensorflow1版本的&#xff0c;发个记录&#xff01; 二、命令 conda create -n tf python3.6 #创建tensorflow虚拟环境 activate tf #激活环境&#xff0c;每次使用的时候都…

【c语言】玩转文件操作

&#x1f31f;&#x1f31f;作者主页&#xff1a;ephemerals__ &#x1f31f;&#x1f31f;所属专栏&#xff1a;C语言 目录 引言 一、文件的打开和关闭 1.流 2.标准流 3.文本文件和二进制文件 4.控制文件打开与关闭的函数 二、文件的顺序读写 三、文件的随机读写 1…

Mac本地部署大模型-单机运行

前些天在一台linux服务器&#xff08;8核&#xff0c;32G内存&#xff0c;无显卡&#xff09;使用ollama运行阿里通义千问Qwen1.5和Qwen2.0低参数版本大模型&#xff0c;Qwen2-1.5B可以运行&#xff0c;但是推理速度有些慢。 一直还没有尝试在macbook上运行测试大模型&#xf…

PostgreSQL主从同步

目录 一、主从复制原理 二、配置主数据库 2.1 创建同步账号 2.2 配置同步账号访问控制 2.3 设置同步参数 3.4 重启主数据库 三、配置从数据库 3.1 停止从库 3.2 清空从库数据文件 3.3 拉取主库数据文件 3.4 配置从库同步参数 3.5 启动从库 四、测试主从 4.1在主库…

前端JS特效第24集:jquery css3实现瀑布流照片墙特效

jquery css3实现瀑布流照片墙特效&#xff0c;先来看看效果&#xff1a; 部分核心的代码如下(全部代码在文章末尾)&#xff1a; <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8" /> <title>jquerycss3实现瀑…

Studying-代码随想录训练营day31| 56.合并区间、738.单调递增的数字、968.监控二叉树、贪心算法总结

第31天&#xff0c;贪心最后一节(ง •_•)ง&#x1f4aa;&#xff0c;编程语言&#xff1a;C 目录 56.合并区间 738.单调递增的数字 968.监控二叉树 贪心算法总结 56.合并区间 文档讲解&#xff1a;代码随想录合并区间 视频讲解&#xff1a;手撕合并区间 题目&#xf…

firewalld(6)自定义services、ipset

简介 在前面的文章中我们已经介绍了zone、rich rule 、--direct等功能和基本配置。在前面文章中&#xff0c;我们提到过firewalld内置了很多服务&#xff0c;可以通过firewall-cmd --get-services来查看服务&#xff0c;也可以通过配置文件查看这些服务/var/lib/firewalld/ser…

直面生产制造的8大核心痛点

1.制造部门的计划紊乱问题 1.1计划的重要性与常见缺陷 计划是制造部门高效运作的前提。在实际运作中&#xff0c;计划的缺失或不周会导致生产效率的大幅降低。常见缺陷包括&#xff1a; -缺乏综合的生产计划&#xff0c;过分依赖销售计划&#xff0c;忽视生产和采购的实际能…

盘点2024年6月Sui生态发展,了解Sui近期成长历程

随着区块链技术的迅猛发展&#xff0c;Sui生态在2024年6月取得了令人欣喜的进步。作为创新的L1协议&#xff0c;Sui不仅在技术革新方面表现突出&#xff0c;还在DeFi、游戏应用和开发者工具等领域展现出强大的潜力。本篇文章将全面盘点Sui在过去一个月内的生态发展&#xff0c;…

堆溢出ret2libc

堆溢出–ret2libc 题目&#xff1a; [HNCTF 2022 WEEK4]ezheap | NSSCTF 讲解&#xff1a; 题目保护全开&#xff0c;要泄漏基地址&#xff1a; 利用栈溢出覆盖put参数泄漏libc基地址&#xff0c;再第二次用system的地址覆盖put函数&#xff0c;实现ret2libc。 泄漏libc…

Redis源码整体结构

一 前言 Redis源码研究为什么先介绍整体结构呢?其实也很简单,作为程序员的,要想对一个项目有快速的认知,对项目整体目录结构有一个清晰认识,有助于我们更好的了解这个系统。 二 目录结构 Redis源码download到本地之后,对应结构如下: 从上面的截图可以看出,Redis源码一…

文华财经盘立方期货通鳄鱼指标公式均线交易策略源码

文华财经盘立方期货通鳄鱼指标公式均线交易策略源码&#xff1a; 新建主图幅图类型指标都可以&#xff01; VAR1:(HL)/2; 唇:REF(SMA(VAR1,5,1),3),COLORGREEN; 齿:REF(SMA(VAR1,8,1),5),COLORRED; 颚:REF(SMA(VAR1,13,1),8),COLORBLUE;

Gemini for China 大更新,现已上架 Android APP!

官网&#xff1a;https://gemini.fostmar.online/ Android APP&#xff1a;https://gemini.fostmar.online/gemini_1.0.apk 一、Android APP 如果是 Android 设备&#xff0c;则会直接识别到并给下载链接。PC 直接对话即可。 二、聊天记录 现在 Gemini for China&#xff…

开始尝试从0写一个项目--后端(二)

实现学生管理 新增学生 接口设计 请求路径&#xff1a;/admin/student 请求方法&#xff1a;POST 请求参数&#xff1a;请求头&#xff1a;Headers&#xff1a;"Content-Type": "application/json" 请求体&#xff1a;Body&#xff1a; id 学生id …

计算机网络性能指标概述:速率、带宽、时延等

在计算机网络中&#xff0c;性能指标是衡量网络效率和质量的重要参数。本文将综合三篇关于计算机网络性能指标的文章&#xff0c;详细介绍速率、带宽、吞吐量、时延、时延带宽积、往返时延&#xff08;RTT&#xff09; 和利用率的概念及其在网络中的应用。 1. 速率&#xff08;…