参考:https://www.alsa-project.org/alsa-doc/alsa-lib/_2test_2pcm_8c-example.html

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <alsa/asoundlib.h>
#include <unistd.h> typedef struct {
char *file_name;
char *device;
int ch;
int bit;
int rate;
snd_pcm_format_t format;
unsigned int buffer_time;
unsigned int period_time;
snd_pcm_uframes_t buffer;
snd_pcm_uframes_t period;
}CONFIG_T; typedef struct {
char id[];
int size;
}RIFF_HEADER_T; typedef struct {
char format[];
char sub_id_1[];
int sub_size_1;
short fmt;
short ch;
int sample_rate;
int byte_rate;
short block_align;
short bits_per_sample;
}WAVE_HEADER_T; typedef struct {
char sub_id_2[];
int sub_size_2;
}DATA_HEADER_T; RIFF_HEADER_T riff_header;
WAVE_HEADER_T wave_header;
DATA_HEADER_T data_header;
CONFIG_T config; static void help(void)
{
printf(
"Usage: pcm [OPTION]... [FILE]...\n"
"-h,--help help\n"
"-D,--device playback device\n"
"-i,--input_file only support wav file\n"
"\n");
} static void parse_cmd(int argc, char **argv)
{
struct option long_option[] =
{
{"help", , NULL, 'h'},
{"device", , NULL, 'D'},
{"input_file", , NULL, 'i'},
{NULL, , NULL, },
};
while () {
int c;
if ((c = getopt_long(argc, argv, "hD:i:", long_option, NULL)) < )
break;
switch (c) {
case 'h':
help();
break;
case 'D':
config.device = strdup(optarg);
break;
case 'i':
config.file_name = strdup(optarg);
break;
}
}
} static snd_pcm_format_t get_format(int bits_per_sample)
{
snd_pcm_format_t format = SND_PCM_FORMAT_S8;
switch(bits_per_sample) {
case :
format = SND_PCM_FORMAT_S8;
break;
case :
format = SND_PCM_FORMAT_S16_LE;
break;
case :
format = SND_PCM_FORMAT_S24_LE;
break;
case :
format = SND_PCM_FORMAT_S32_LE;
break;
}
return format;
} static int config_init(CONFIG_T *pConfig)
{
FILE *fp = NULL;
if (NULL == pConfig) {
return -;
}
fp = fopen(pConfig->file_name, "rb");
if (NULL == fp) {
return -;
} fread((void *)&riff_header, sizeof(RIFF_HEADER_T), , fp);
fread((void *)&wave_header, sizeof(WAVE_HEADER_T), , fp);
if (wave_header.sub_size_1 > sizeof (WAVE_HEADER_T) -)
fseek(fp, wave_header.sub_size_1 - (sizeof (WAVE_HEADER_T) - ), SEEK_CUR);
fread((void *)&data_header, sizeof(DATA_HEADER_T), , fp);
pConfig->ch = wave_header.ch;
pConfig->rate= wave_header.sample_rate;
pConfig->bit= wave_header.bits_per_sample;
pConfig->format = get_format(wave_header.bits_per_sample);
fclose(fp);
return ;
} static int set_hwparams(snd_pcm_t *handle)
{
snd_pcm_hw_params_t *params;
unsigned int rrate;
snd_pcm_uframes_t size;
int err, dir;
snd_pcm_hw_params_alloca(&params);
/* choose all parameters */
err = snd_pcm_hw_params_any(handle, params);
if (err < ) {
printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
return err;
}
/* set the interleaved read/write format */
err = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
if (err < ) {
printf("Access type not available for playback: %s\n", snd_strerror(err));
return err;
}
/* set the sample format */
err = snd_pcm_hw_params_set_format(handle, params, config.format);
if (err < ) {
printf("Sample format not available for playback: %s\n", snd_strerror(err));
return err;
}
/* set the count of channels */
err = snd_pcm_hw_params_set_channels(handle, params, config.ch);
if (err < ) {
printf("Channels count (%u) not available for playbacks: %s\n", config.ch, snd_strerror(err));
return err;
}
/* set the stream rate */
rrate = config.rate;
err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, );
if (err < ) {
printf("Rate %uHz not available for playback: %s\n", config.rate, snd_strerror(err));
return err;
}
if (rrate != config.rate) {
printf("Rate doesn't match (requested %uHz, get %iHz)\n", config.rate, err);
return -EINVAL;
}
/* set the buffer time */
err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &config.buffer_time, &dir);
if (err < ) {
printf("Unable to set buffer time %u for playback: %s\n", config.buffer_time, snd_strerror(err));
return err;
}
err = snd_pcm_hw_params_get_buffer_size(params, &size);
if (err < ) {
printf("Unable to get buffer size for playback: %s\n", snd_strerror(err));
return err;
}
config.buffer = size;
/* set the period time */
err = snd_pcm_hw_params_set_period_time_near(handle, params, &config.period_time, &dir);
if (err < ) {
printf("Unable to set period time %u for playback: %s\n", config.period_time, snd_strerror(err));
return err;
}
err = snd_pcm_hw_params_get_period_size(params, &size, &dir);
if (err < ) {
printf("Unable to get period size for playback: %s\n", snd_strerror(err));
return err;
}
config.period = size;
/* write the parameters to device */
err = snd_pcm_hw_params(handle, params);
if (err < ) {
printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
return err;
}
return ;
}
static int set_swparams(snd_pcm_t *handle)
{
int err;
snd_pcm_sw_params_t *swparams;
snd_pcm_sw_params_alloca(&swparams);
/* get the current swparams */
err = snd_pcm_sw_params_current(handle, swparams);
if (err < ) {
printf("Unable to determine current swparams for playback: %s\n", snd_strerror(err));
return err;
}
/* start the transfer when the buffer is almost full: */
/* (buffer_size / avail_min) * avail_min */
err = snd_pcm_sw_params_set_start_threshold(handle, swparams, (config.buffer / config.period) * config.period);
if (err < ) {
printf("Unable to set start threshold mode for playback: %s\n", snd_strerror(err));
return err;
} /* write the parameters to the playback device */
err = snd_pcm_sw_params(handle, swparams);
if (err < ) {
printf("Unable to set sw params for playback: %s\n", snd_strerror(err));
return err;
}
return ;
} /*
* Underrun and suspend recovery
*/ static int xrun_recovery(snd_pcm_t *handle, int err)
{
printf("stream recovery\n");
if (err == -EPIPE) { /* under-run */
err = snd_pcm_prepare(handle);
if (err < )
printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
return ;
} else if (err == -ESTRPIPE) {
while ((err = snd_pcm_resume(handle)) == -EAGAIN)
sleep(); /* wait until the suspend flag is released */
if (err < ) {
err = snd_pcm_prepare(handle);
if (err < )
printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
}
return ;
}
return err;
} static int write_loop(snd_pcm_t *handle)
{
int err;
size_t remain, read_size;
FILE *fp = NULL;
char *read_buffer = NULL, *offset = NULL;
int bytes_per_frame = config.ch * (config.bit >> );
read_size = config.period * bytes_per_frame;
fp = fopen(config.file_name, "rb");
if (NULL == fp) {
return -;
}
read_buffer = (char * )malloc(read_size);
fseek(fp, , SEEK_CUR); while () {
memset(read_buffer ,, read_size);
err = fread(read_buffer ,, read_size, fp);
if (err <= )
break;
offset = read_buffer;
remain = err / bytes_per_frame;
while (remain> ) {
err = snd_pcm_writei(handle, offset, remain);
if (err == -EAGAIN)
continue;
if (err < ) {
if (xrun_recovery(handle, err) < ) {
printf("Write error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
continue;
}
offset += err * bytes_per_frame;
remain -= err;
}
}
free(read_buffer);
fclose(fp);
return ;
} int main(int argc, char **argv)
{
int err = ;
snd_pcm_t *handle;
memset (&config, , sizeof(CONFIG_T));
config.buffer_time = ;//us
config.period_time = ;
parse_cmd(argc, argv);
config_init(&config);
if ((err = snd_pcm_open(&handle, config.device, SND_PCM_STREAM_PLAYBACK, )) < ) {
printf("Playback open error: %s\n", snd_strerror(err));
return ;
} if ((err = set_hwparams(handle)) < ) {
printf("Setting of hwparams failed: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
if ((err = set_swparams(handle)) < ) {
printf("Setting of swparams failed: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
write_loop(handle);
snd_pcm_close(handle);
return 0;
}

Makefile:

ALSA_INC_PATH=/home/fellow/alsa-lib-1.2./output/usr/include
ALSA_LIB_PATH=/usr/lib/i386-linux-gnu
ALSA_PLUG_PATH=/usr/lib/i386-linux-gnu/alsa-lib export LD_LIBRARY_PATH=${ALSA_LIB_PATH}:${ALSA_PLUG_PATH}:$LD_LIBRARY_PATH
export CC=gcc
export CFLAGS=-I${ALSA_INC_PATH}
export LDFLAGS=-L{ALSA_LIB_PATH} -lasound
SOURCE=alsa_test.c
TARGET=alsa_test
all:
${CC} ${SOURCE} ${CFLAGS} ${LDFLAGS} -o ${TARGET}

./alsa_test -D default -i xx.wav

ALSA Lib-简单的播放例子的更多相关文章

  1. lib和dll的例子

    .dll和.lib的区别 lib是静态库,dll一般是动态链接库(也有可能是别的)比如要编译个exe,lib在编译的时候就会被编译到exe里,作为程序的一部分而dll是不被编译进去,是运行的时候才调入 ...

  2. 一个简单的cmake例子

    一个简单的cmake例子CMakeLists.txt,生成动态库文件,可以指定发布目录. 尚不支持: 1.交叉编译环境配置 2.添加依赖库   #在当前目录新建一个build目录,然后cd build ...

  3. ALSA lib基本概念

    1.channel 通道,即我们熟知的声道数.左/右声道,5.1channel等等 2.sample A sample is a single value that describes the amp ...

  4. Android开发6:Service的使用(简单音乐播放器的实现)

    前言 啦啦啦~各位好久不见啦~博主最近比较忙,而且最近一次实验也是刚刚结束~ 好了不废话了,直接进入我们这次的内容~ 在这篇博文里我们将学习Service(服务)的相关知识,学会使用 Service ...

  5. Android 实现简单音乐播放器(二)

    在Android 实现简单音乐播放器(一)中,我介绍了MusicPlayer的页面设计. 现在,我简单总结一些功能实现过程中的要点和有趣的细节,结合MainActivity.java代码进行说明(写出 ...

  6. Android 实现简单音乐播放器(一)

    今天掐指一算,学习Android长达近两个月了,今天开始,对过去一段时间的学习收获以及遇到的疑难杂症做一些总结. 简单音乐播放器是我自己完成的第一个功能较为完整的APP,可以说是我的Android学习 ...

  7. html5 简单音乐播放器

    html5 简单音乐播放器 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> < ...

  8. 一个简单的CORBA例子

    因为对CORBA分析的需要,这里写一个简单的CORBA例子.从JDK1.2开始,JDK中集成了ORB的实现,本例子使用了JDK1.7,对于JDK1.2+应该都没有问题.这个例子实现一个简单的加减乘除的 ...

  9. 菜鸟学习Hibernate——简单的一个例子

    一.Hibernate开发. 上篇博客已经为大家介绍了持久层框架的发展流程,持久层框架的种类. 为了能够使用Hibernate快速上手,我们先讲解一个简单的Hibernate应用实例hibernate ...

随机推荐

  1. Thread Based Parallelism - Thread Synchronization With Lock

    Thread Based Parallelism - Thread Synchronization With Lock import threading shared_resource_with_lo ...

  2. MySQL8.0 InnoDB并行执行

    概述 MySQL经过多年的发展已然成为最流行的数据库,广泛用于互联网行业,并逐步向各个传统行业渗透.之所以流行,一方面是其优秀的高并发事务处理的能力,另一方面也得益于MySQL丰富的生态.MySQL在 ...

  3. 工程引用libm.a文件的sin函数后

    更改前后的main.c //#include <math.h> ; int var_bss; int main() { double d; // d = sin(3.14/2); ; } ...

  4. redis系列-开篇

    0x0 缘起 笔者所在的公司有一款大DAU(日活)的休闲游戏.这款游戏的后端架构很简单,可以简单理解为通讯-逻辑-存储三层结构.其中存储层大量使用了redis和mysql. 虽然存量用户的增加,red ...

  5. StarUML之六、StarUML规则与快捷键

    本章内容参考官网即可,不做详细说明,实践出真知! starUMl规则主要是在模型设计的约束条件 https://docs.staruml.io/user-guide/validation-rules ...

  6. JS中this的几种情况

    1.给元素的某个事件行为绑定方法,事件触发,方法执行,此时方法中的this一般都是当前元素本身: <div id="div"></div> div.oncl ...

  7. CSS中元素的显示模式

     在CSS中,根据元素显示模式的不同元素标签被分为了两类:行内元素(inline-level).块级元素(block-level). 1,首先介绍什么是行内元素,什么又是块级元素? 1.1,行内元素就 ...

  8. 关于elementui的table组件单元格的内容自定义写法

    ------------恢复内容开始------------ 记录老哥的写法 columns是表格的配置文件 在表格渲染的时候通过renderTableCell传入表格的row以及配置文件中的rend ...

  9. 【python数据挖掘】爬取豆瓣影评数据

    概述: 爬取豆瓣影评数据步骤: 1.获取网页请求 2.解析获取的网页 3.提速数据 4.保存文件 源代码: # 1.导入需要的库 import urllib.request from bs4 impo ...

  10. 将Markdown编辑器搬进您的博客-让我们更优雅的书写文章

    各位小伙伴们,冷月今天给大家发一波福利.我们都知道markdown编辑器非常的好用,是我们写作的好帮手.这样的一款好用的文章编辑器,我们怎么才能让自己的博客也支持呢,冷月今天来教大家如何将Markdo ...