Playing Sound
对应教程地址Tutorial 03: Playing Sound
参考博客:最简单的基于FFMPEG+SDL的音频播放器 ver2 (采用SDL2.0)
这段代码在VS2015上编译通过,文件格式是.c,不是.cpp。
这段代码跟官网上的有部分不同,是因为音频解码以后,需要转换,SDL才能播放出来
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
#include <libavutil/samplefmt.h>
#include <libswresample/swresample.h>
#include <SDL.h>
#include <SDL_thread.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#define MAX_AUDIO_FRAME_SIZE 192000;
#define SDL_AUDIO_BUFFER_SIZE 1024;
typedef struct
{
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
SDL_mutex *mutext;
SDL_cond *cond;
}PacketQueue;
int g_quit = 0;
PacketQueue audioq;
AVFrame wanted_frame;
void audio_callback(void *userdata, Uint8 *stream, int len);
void packet_queue_init(PacketQueue *q);
int packet_queue_put(PacketQueue *q, AVPacket *pkt);
int packet_queue_get(PacketQueue* q, AVPacket* pkt, int block);
int audio_decode_frame(AVCodecContext *aCodecCtx, uint8_t *audio_buf, int buf_size);
int main(int argc, char **argv)
{
AVFormatContext *pFormateCtx = NULL;
AVCodecContext *pCodecCtxOrig = NULL;
AVCodecParameters *videoCodecParameter;
AVCodecParameters *audioCodecParameter;
AVCodecContext *pAudioCodecCtxOrig = NULL;
AVCodec *pCodec = NULL;
AVCodec *pAudioCodec = NULL;
AVFrame *pFrame = NULL;
AVFrame *pFrameRGB = NULL;
uint8_t *buffer = NULL;
int numBytes;
int videoStream = -1;
int audioStream = -1;
struct SwsContext *sws_cts = NULL;
int i;
int ret;
SDL_Window *screen;
SDL_Surface *surface;
SDL_Renderer* renderer;
SDL_Texture* testexture;
SDL_Event event;
SDL_Rect rect;
SDL_AudioSpec wanted_spec, spec;
char filePath[256] = { 0 };
if (argc < 2)
{
printf("Please input video name:");
gets_s(filePath, 256);
}
else
{
strcpy_s(filePath, 256, argv[1]);
}
//初始化
av_register_all();
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER))
{
printf_s("SDL_Init failed:%s\n", SDL_GetError());
return -1;
}
//读取文件头和存储信息到pFormateCtx中
if (avformat_open_input(&pFormateCtx, filePath, NULL, 0) != 0)
{
printf_s("avformat_open_input failed\n");
return -1;
}
if (avformat_find_stream_info(pFormateCtx, NULL) < 0)
{
printf_s("avformat_find_stream_info failed\n");
return -1;
}
av_dump_format(pFormateCtx, 0, filePath, 0);