这里以常用的视频原始数据PCM数据为例,展示音频的播放。
SDL播放音频的流程如下:
SDL_AudioSpec:
typedef struct SDL_AudioSpec {
int freq; // 音频采样率
SDL_AudioFormat format; // 音频数据格式
Uint8 channels; // 声道数: 1 单声道, 2 立体声
Uint8 silence; // 设置静音的值,因为声音采样是有符号的,所以0当然就是这个值
Uint16 samples; // 音频缓冲区中的采样个数,要求必须是2的n次,这个决定了回调len的长度,len=samples*chn*位宽(单位是字节)
Uint16 padding; // 考虑到兼容性的一个参数
Uint32 size; // 音频缓冲区的大小,以字节为单位
SDL_AudioCallback callback; // 填充音频缓冲区的回调函数
void *userdata; // 用户自定义的数据
} SDL_AudioSpec;
SDL_AudioCallback回调:
typedef void (SDLCALL * SDL_AudioCallback) (void *userdata, Uint8 * stream,
int len);
播放音频数据:
// 当pause_on设置为0的时候即可开始播放音频数据。设置为1的时候,将会播放静音的值。
void SDLCALL SDL_PauseAudio(int pause_on)
混音函数:
extern DECLSPEC void SDLCALL SDL_MixAudio(Uint8 * dst, const Uint8 * src,
Uint32 len, int volume);
#include
#include
static Uint8 *audio_chunk;
static Uint32 audio_len;
static Uint8 *audio_pos;
void fill_audio(void *udata, Uint8 *stream, int len)
{
//SDL 2.0
SDL_memset(stream, 0, len);
if (audio_len == 0) /* Only play if we have data left */
return;
len = (len > audio_len ? audio_len : len); /* Mix as much data as possible */
SDL_MixAudio(stream, audio_pos, len, SDL_MIX_MAXVOLUME);
audio_pos += len;
audio_len -= len;
}
#undef main
int main(int argc, char* argv[])
{
//Init
if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_TIMER))
{
printf("Could not initialize SDL - %s\n", SDL_GetError());
return -1;
}
//SDL_AudioSpec
SDL_AudioSpec wanted_spec;
wanted_spec.freq = 44100;
wanted_spec.format = AUDIO_S16SYS;
wanted_spec.channels = 2;
wanted_spec.silence = 0;
wanted_spec.samples = 1024;
wanted_spec.callback = fill_audio;
//打开音频设备
if (SDL_OpenAudio(&wanted_spec, NULL) < 0)
{
printf("can't open audio.\n");
return -1;
}
FILE *fp = fopen("./test.pcm", "rb+");
if (fp == NULL)
{
printf("cannot open this file\n");
return -1;
}
//For YUV420P
int pcm_buffer_size = 4096;
char *pcm_buffer = (char *)malloc(pcm_buffer_size);
int data_count = 0;
while (1)
{
if (fread(pcm_buffer, 1, pcm_buffer_size, fp) != pcm_buffer_size)
{
// Loop
fseek(fp, 0, SEEK_SET);
fread(pcm_buffer, 1, pcm_buffer_size, fp);
data_count = 0;
}
printf("Now Playing %10d Bytes data.\n", data_count);
data_count += pcm_buffer_size;
//Set audio buffer (PCM data)
audio_chunk = (Uint8 *)pcm_buffer;
//Audio buffer length
audio_len = pcm_buffer_size;
audio_pos = audio_chunk;
//Play
SDL_PauseAudio(0);
while (audio_len > 0)//Wait until finish
SDL_Delay(1);
}
fclose(fp);
SDL_CloseAudio();
SDL_Quit();
return 0;
}
[总结]FFMPEG视音频编解码零基础学习方法_零基础ffmpeg 雷霄骅-CSDN博客
FFmpeg 音频解码(秒懂)-CSDN博客
SDL2 播放视频文件(MP4)-CSDN博客
SDL2 播放音频(MP4)-CSDN博客