生成 pcm 音频
- mp3 截取
$ ffmpeg -i test.mp3 -ss 00:00:10 -t 00:00:30 -acodec copy cut.mp3
-acodec copy 编码格式复制
- mp3 转 pcm
$ ffmpeg -i cut.mp3 -acodec pcm_s16le -f s16le -ac 2 -ar 44100 test.pcm
-f 强制文件格式 -ac 通道数 -ar 采用率
源代码
-
demo.c
#include <SDL2/SDL.h> #include <stdio.h> /** * @brief SDL2 获取音频的回调函数 * @param userdata 用户数据 * @param stream 音频缓冲区 * @param len 音频长度 */ void fill_audio_cb(void *userdata, Uint8 * stream, int len) { FILE **fpp = (FILE**)userdata; if(fpp == NULL || *fpp == NULL || len == 0) { return ; } SDL_memset(stream, 0, len); if(fread(stream, 1, len, *fpp) != len) { printf("Play Done! Replay\n"); fseek(*fpp, 0, SEEK_SET); } } int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_AUDIO | SDL_INIT_TIMER); FILE *audio_file = NULL; SDL_AudioSpec aduio_spec = { .format = AUDIO_S16LSB, /* 音频格式 signed 16bit LSB */ .freq = 44100, /* 采样率 */ .channels = 2, /* 通道数 */ .silence = 0, /* 静音值 */ .callback = fill_audio_cb, /* 回调函数 */ .userdata = &audio_file /* 回调函数用户数据 */ }; if ((audio_file = fopen("test.pcm", "rb")) == NULL) { printf("Cannot open this file\n"); return -1; } if (SDL_OpenAudio(&aduio_spec, NULL) < 0) { printf("Can't open audio.\n"); fclose(audio_file); return -1; } printf("Start to play, return to exit\n"); SDL_PauseAudio(0); getchar(); fclose(audio_file); SDL_Quit(); return 0; }
-
编译运行(mingw 环境)
$ gcc demo.c -lmingw32 -lSDL2main -lSDL2 $ ./a.exe Start to play, return to exit