---
title: "ffmpeg + sdl -03 简单音频播放器实现"
author: "he91_com"
date: "2013-09-26T00:08:00Z"
tags: []
slug: "ffmpeg-sdl-03"
draft: false
lastmod: "2013-09-26T18:07:29Z"
id: 1947869
url: "https://he91-com.iteye.com/blog/1947869"
---

没办法，工作中遇到了问题。

目前NEC EMMA的架构如下：

从USB读入文件 -&gt; 文件分析并提取Packet中的Payload Data -&gt; NEC HANDLE AVTransfer -&gt; NEC HANDLE WMV -&gt; AUDIO OUTPUT

按照驱动的API写好代码后却怎么也没有声音，所有API返回值均OK。

郁闷开始了。继续绝望中寻找希望。

为了对比调试，参考

[http://blog.csdn.net/ashlingr/article/details/7791321](http://blog.csdn.net/ashlingr/article/details/7791321)

并做了一些ffmpeg版本升级修改。

修改前：

1. len=avcodec\_decode\_audio(pAudioCodecCtx,
2. (int16\_t\*)decompressed\_audio\_buf,
3. &decompressed\_audio\_buf\_size,//itisthedecompressedframeinBYTES解码后的数据大小，字节为单位；
4. packet.data,
5. packet.size);

修改后：

decompressed\_audio\_buf\_size = (AVCODEC\_MAX\_AUDIO\_FRAME\_SIZE * 3) / 2; // 不加这一行，执行时会出错。

len = avcodec\_decode\_audio3 (pCodecCtx,

(int16\_t \*)decompressed\_audio\_buf,

&decompressed\_audio\_buf\_size, // it is the decompressed frame in BYTES

&packet);

遇到的问题：

/dev/dsp 设备不存在

解决办法：

modprobe snd\_pcm\_oss （需要su到root用户）

完整代码如下：（基本来自[http://bbs.chinavideo.org/viewthread.php?tid=1247&extra=page%3D1](http://bbs.chinavideo.org/viewthread.php?tid=1247&extra=page%3D1)）

#include &lt;avcodec.h&gt;  
#include &lt;avformat.h&gt;  
#include &lt;avutil.h&gt;  
#include &lt;assert.h&gt;  
#include &lt;stdio.h&gt;  
#include &lt;stdlib.h&gt;  
#include &lt;X11/Xlib.h&gt;  
#include &lt;sys/soundcard.h&gt;  
#include &lt;sys/stat.h&gt;  
#include &lt;fcntl.h&gt;  
#include &lt;sys/ioctl.h&gt;  
#include &lt;unistd.h&gt;  
#include &lt;errno.h&gt;  
#include &lt;string.h&gt;  
#include &lt;sched.h&gt;

#define ALL\_DEBUG

#ifdef ALL\_DEBUG  
#define AV\_DEBUG  
#define AUDIO\_DEBUG  
#endif

//------------------------------------------------------------------------------  
// manipulations for file  
int open\_file (char \*file\_name, int mode)  
{  
// open file file\_name and return the file descriptor;  
int fd;

if ((fd = open (file\_name, mode)) &lt; 0)  
{  
fprintf (stderr, " Can't open %s!/n", file\_name);  
exit (-1);  
}  
return fd;  
}

int set\_audio (int fd, AVCodecContext * pCodecCtx)  
{  
// set the properties of audio device with pCodecCtx;

int i, err;  
/* 设置适当的参数，使得声音设备工作正常 \*/  
/* 详细情况请参考Linux关于声卡编程的文档 \*/

i = 0;  
ioctl (fd, SNDCTL\_DSP\_RESET, &i);  
i = 0;  
ioctl (fd, SNDCTL\_DSP\_SYNC, &i);  
i = 1;  
ioctl (fd, SNDCTL\_DSP\_NONBLOCK, &i);

// set sample rate;  
#ifdef AUDIO\_DEBUG  
printf ("pCodecCtx-&gt;sample\_rate:%d/n", pCodecCtx-&gt;sample\_rate);  
#endif  
i = pCodecCtx-&gt;sample\_rate;  
if (ioctl (fd, SNDCTL\_DSP\_SPEED, &i) == -1)  
{  
fprintf (stderr, "Set speed to %d failed:%s/n", i,  
strerror (errno));  
return (-1);  
}  
if (i != pCodecCtx-&gt;sample\_rate)  
{  
fprintf (stderr, "do not support speed %d,supported is %d/n",  
pCodecCtx-&gt;sample\_rate, i);  
return (-1);  
}

// set channels;  
i = pCodecCtx-&gt;channels;  
#ifdef AUDIO\_DEBUG  
printf ("pCodecCtx-&gt;channels:%d/n", pCodecCtx-&gt;channels);  
#endif  
if ((ioctl (fd, SNDCTL\_DSP\_CHANNELS, &i)) == -1)  
{  
fprintf (stderr, "Set Audio Channels %d failed:%s/n", i,  
strerror (errno));  
return (-1);  
}  
if (i != pCodecCtx-&gt;channels)  
{  
fprintf (stderr, "do not support channel %d,supported %d/n",  
pCodecCtx-&gt;channels, i);  
return (-1);  
}  
// set bit format;  
i = AFMT\_S16\_LE;  
if (ioctl (fd, SNDCTL\_DSP\_SETFMT, &i) == -1)  
{  
fprintf (stderr, "Set fmt to bit %d failed:%s/n", i,  
strerror (errno));  
return (-1);  
}  
if (i != AFMT\_S16\_LE)  
{  
fprintf (stderr, "do not support bit %d, supported %d/n",  
AFMT\_S16\_LE, i);  
return (-1);  
}

// set application buffer size;  
// i = (0x00032 &lt;&lt; 16) + 0x000c; // 32 4kb buffer;  
// ioctl (fd, SNDCTL\_DSP\_SETFRAGMENT, &i);  
i = 1;  
ioctl (fd, SNDCTL\_DSP\_PROFILE, &i);

return 0;  
}

void close\_file (int fd)  
{  
// close the file pointed by file descriptor fd;  
close (fd);  
}

//------------------------------------------------------------------------------  
// handle audio;

void display\_AVCodecContext(AVCodecContext \*pCodecCtx){  
//  
#define STDOUT stderr  
fprintf(STDOUT, "pCodecCtx-&gt;bit\_rate:%d/n", pCodecCtx-&gt;bit\_rate);  
fprintf(STDOUT, "pCodecCtx-&gt;sample\_rate:%d/n", pCodecCtx-&gt;sample\_rate);  
fprintf(STDOUT, "pCodecCtx-&gt;channels:%d/n", pCodecCtx-&gt;channels);  
fprintf(STDOUT, "pCodecCtx-&gt;frame\_size:%d/n", pCodecCtx-&gt;frame\_size);  
fprintf(STDOUT, "pCodecCtx-&gt;frame\_number:%d/n", pCodecCtx-&gt;frame\_number);  
fprintf(STDOUT, "pCodecCtx-&gt;delay:%d/n", pCodecCtx-&gt;delay);  
fprintf(STDOUT, "pCodecCtx-&gt;frame\_bits:%d/n", pCodecCtx-&gt;frame\_bits);  
}

// error if return -1;  
// success if return 0;  
// 这里要用到指向指针的指针，否则传不到值；  
int av\_init (char \*file\_name, AVFormatContext \** pFormatCtx,  
AVCodecContext \** pCodecCtx, int \*p\_audioStream)  
{  
// init the codec and format of input file file\_name;  
int audioStream, i;  
AVCodec \*pCodec;  
// catch error  
assert(file\_name != NULL);  
assert(\*pFormatCtx != NULL);  
assert(\*pCodecCtx != NULL);

// Register all formats and codecs  
av\_register\_all ();

// open file  
if (av\_open\_input\_file (pFormatCtx, file\_name, NULL, 0, NULL) != 0){  
// Couldn't open file  
fprintf (stderr, " Can't open %s!/n", file\_name);  
return -1;  
}

// Retrieve stream information  
if (av\_find\_stream\_info (\*pFormatCtx) &lt; 0){  
// Couldn't find stream information  
return -1;  
}

#ifdef AV\_DEBUG  
// Dump information about file onto standard error  
dump\_format (\*pFormatCtx, 0, file\_name, 0);  
#endif

// Find the first audio and video stream respectively  
audioStream = -1;  
for (i = 0; i &lt; (\*pFormatCtx)-&gt;nb\_streams; i++){  
if ((\*pFormatCtx)-&gt;streams\[i]-&gt;codec-&gt;codec\_type ==  
AVMEDIA\_TYPE\_AUDIO)  
{  
audioStream = i;  
}  
}

#ifdef AV\_DEBUG  
// dump\_stream\_info(pFormatCtx);  
#endif

// exclude error  
if (audioStream == -1){  
// Didn't find a audio or video stream  
return -1;  
}

// Get a pointer to the codec context for the audio stream  
\*pCodecCtx = (\*pFormatCtx)-&gt;streams\[audioStream]-&gt;codec;

// Find the decoder for the audio stream  
pCodec = avcodec\_find\_decoder ((\*pCodecCtx)-&gt;codec\_id);  
if (pCodec == NULL)  
return -1; // Codec not found

// Open codec  
if (avcodec\_open ((\*pCodecCtx), pCodec) &lt; 0){  
return -1; // Could not open codec  
}

#ifdef AUDIO\_DEBUG  
// printf ("pCodecCtx-&gt;sample\_rate:%d, audioStream:%d/n", (\*pCodecCtx)-&gt;sample\_rate, audioStream);  
// display\_AVCodecContext(\*pCodecCtx);  
#endif

\*p\_audioStream = audioStream;

return 0;  
}

void av\_play (AVFormatContext * pFormatCtx,  
AVCodecContext * pCodecCtx, int audioStream)  
{  
// which was read from one frame;  
AVPacket packet;  
uint32\_t len;  
uint8\_t decompressed\_audio\_buf\[(AVCODEC\_MAX\_AUDIO\_FRAME\_SIZE * 3) / 2];  
int decompressed\_audio\_buf\_size;  
uint8\_t * p\_decompressed\_audio\_buf;  
int fd = -1; // audio file or test file?  
char filename\[64] = "/dev/dsp";  
int mode = O\_WRONLY;  
//

// open audio file or written file  
// printf("fd:%d", fd);  
fd = open\_file(filename, mode);  
printf("fd:%d \\n", fd);  
//  
set\_audio(fd, pCodecCtx);

//  
printf("(AVCODEC\_MAX\_AUDIO\_FRAME\_SIZE * 3) / 2=%d\\n", (AVCODEC\_MAX\_AUDIO\_FRAME\_SIZE * 3) / 2);  
printf("AVCODEC\_MAX\_AUDIO\_FRAME\_SIZE=%d\\n", AVCODEC\_MAX\_AUDIO\_FRAME\_SIZE);

// for a test  
// char test\_file\[256] = "my\_pcm.pcm";  
// fd = open\_file(test\_file, mode);

#ifdef AV\_DEBUG  
static int size = 0;  
#endif  
//

// set the sched priority  
// 这是为了提高音频优先级；不晓得起作用没；  
int policy = SCHED\_FIFO;  
sched\_setscheduler(0, policy, NULL);

int write\_buf\_size = 4196;  
int written\_size;  
while (av\_read\_frame (pFormatCtx, &packet) &gt;= 0)  
{  
// Is this a packet from the audio stream?  
// 判断是否音频帧；  
if (packet.stream\_index == audioStream)  
{  
// Decode audio frame  
// 解码音频数据为pcm数据；  
decompressed\_audio\_buf\_size = (AVCODEC\_MAX\_AUDIO\_FRAME\_SIZE * 3) / 2;  
len = avcodec\_decode\_audio3 (pCodecCtx,  
(int16\_t \*)decompressed\_audio\_buf,  
&decompressed\_audio\_buf\_size, // it is the decompressed frame in BYTES  
&packet);  
// printf("len:%d, packet.size:%d/n", len, packet.size);  
if ( len &lt; 0 ){  
// if error len = -1  
printf("+----- error in decoding audio frame\\n");  
// exit(0);  
}  
// test lsosa

// printf("size = %d/n", size);  
//\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
// 重点是这一部分，使用oss播放的代码，之前的数据写是否完整的问题就是出在这里，或者是前面的set\_audio函数设置不正确；  
// audio\_buf\_info info;  
p\_decompressed\_audio\_buf = decompressed\_audio\_buf;  
while ( decompressed\_audio\_buf\_size &gt; 0 ){  
// 解码后数据不为零，则播放之，为零，则；  
written\_size = write(fd, p\_decompressed\_audio\_buf, decompressed\_audio\_buf\_size);  
if ( written\_size == -1 ){  
// printf("error:decompressed\_audio\_buf\_size:%d, decompressed\_audio\_buf\_size:%d, %s/n", /  
// decompressed\_audio\_buf\_size, decompressed\_audio\_buf\_size,strerror(errno));  
// usleep(100);  
continue;  
}  
// printf("decompressed\_audio\_buf\_size:%d, written\_size:%d/n", /  
// decompressed\_audio\_buf\_size, written\_size);  
decompressed\_audio\_buf\_size -= written\_size;  
p\_decompressed\_audio\_buf += written\_size;

}// end while  
//\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
}  
else  
{  
printf("+----- this is not audio frame/n");  
}// end if  
// Free the packet that was allocated by av\_read\_frame  
av\_free\_packet (&packet);  
}// end while of reading one frame;

close\_file(fd);  
}

void av\_close (AVFormatContext * pFormatCtx, AVCodecContext * pCodecCtx)  
{  
// close the file and codec

// Close the codec  
avcodec\_close (pCodecCtx);

// Close the video file  
av\_close\_input\_file (pFormatCtx);  
}

//------------------------------------------------------------------------------

int main (int argc, char \*\*argv){  
//  
AVFormatContext \*pFormatCtx;  
int audioStream = -1;  
AVCodecContext \*pCodecCtx;

// exclude the error about args;  
if ( argc != 2 ){  
printf("please give a file name\\n");  
exit(0);  
}

// 注意：这里要用到指向指针的指针，是因为这个初始化函数需要对指针的地址进行改动，  
// 所以，只有这么做，才能达到目的；  
if ( av\_init(argv\[1], &pFormatCtx, &pCodecCtx, &audioStream) &lt; 0 ){  
//  
fprintf(stderr, "error when av\_init\\n");  
}

// play the audio file  
av\_play(pFormatCtx, pCodecCtx, audioStream);

// close all the opend files  
av\_close(pFormatCtx, pCodecCtx);

}