[FFmpeg学习]windows环境sdl播放音频试验

2024-06-17 06:28

本文主要是介绍[FFmpeg学习]windows环境sdl播放音频试验,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

参考资料:

FFmpeg和SDL2播放mp4_sdl 播放mp4 声音-CSDN博客

SimplePlayer/SimplePlayer.c at master · David1840/SimplePlayer · GitHub

在前面的学习中,通过获得的AVFrame进行了播放画面,

[FFmpeg学习]初级的SDL播放mp4测试-CSDN博客

播放音频原理类似,也是获取AVFrame的信息,


extern "C" {
#include <libavutil/log.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
}
// Simplest FFmpeg Sync Player.cpp : 定义控制台应用程序的入口点。
//#include <stdio.h>
#include <SDL_types.h>
#include "SDL.h"static Uint8* audio_chunk;
static Uint32 audio_len;
static Uint8* audio_pos;#define MAX_AUDIO_FRAME_SIZE 19200//音频设备需要更多数据的时候会调用该回调函数
void read_audio_data(void* udata, Uint8* stream, int len) {fprintf(stderr, "stream addr:%p, audio_len:%d, len:%d\n",stream,audio_len,len);//首先使用SDL_memset()将stream中的数据设置为0SDL_memset(stream, 0, len);if (audio_len == 0)return;len = (len > audio_len ? audio_len : len);SDL_MixAudio(stream, audio_pos, len, SDL_MIX_MAXVOLUME);audio_pos += len;audio_len -= len;
}#undef main
int main(int argc, char* argv[]) {const char* file = "test.mp4";AVFormatContext* pFormatCtx = NULL; //for opening multi-media fileint i, audioStream = -1;AVCodecParameters* pCodecParameters = NULL; //codec contextAVCodecContext* pCodecCtx = NULL;const AVCodec* pCodec = NULL; // the codecerAVFrame* pFrame = NULL;AVPacket* packet;uint8_t* out_buffer;int64_t in_channel_layout;struct SwrContext* au_convert_ctx;if (avformat_open_input(&pFormatCtx, file, NULL, NULL) != 0) {SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to open video file!");return -1; // Couldn't open file}audioStream = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);if (audioStream == -1) {SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Din't find a video stream!");return -1;// Didn't find a video stream}// Get a pointer to the codec context for the video streampCodecParameters = pFormatCtx->streams[audioStream]->codecpar;// Find the decoder for the video streampCodec = avcodec_find_decoder(pCodecParameters->codec_id);if (pCodec == NULL) {SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unsupported codec!\n");return -1; // Codec not found}// Copy contextpCodecCtx = avcodec_alloc_context3(pCodec);if (avcodec_parameters_to_context(pCodecCtx, pCodecParameters) != 0) {SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't copy codec context");return -1;// Error copying codec context}// Open codecif (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to open decoder!\n");return -1; // Could not open codec}packet = (AVPacket*)av_malloc(sizeof(AVPacket));av_init_packet(packet);pFrame = av_frame_alloc();uint64_t out_channel_layout = AV_CH_LAYOUT_STEREO;//输出声道int out_nb_samples = 1024;enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;//输出格式S16int out_sample_rate = 44100;int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);int out_buffer_size = av_samples_get_buffer_size(NULL, out_channels, out_nb_samples, out_sample_fmt, 1);out_buffer = (uint8_t*)av_malloc(MAX_AUDIO_FRAME_SIZE * 2);//Initif (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_TIMER)) {printf("Could not initialize SDL - %s\n", SDL_GetError());return -1;}SDL_AudioSpec spec;spec.freq = out_sample_rate;spec.format = AUDIO_S16SYS;spec.channels = out_channels;spec.silence = 0;spec.samples = out_nb_samples;spec.callback = read_audio_data;spec.userdata = pCodecCtx;if (SDL_OpenAudio(&spec, NULL) < 0) {printf("can't open audio.\n");return -1;}in_channel_layout = av_get_default_channel_layout(pCodecCtx->channels);printf("in_channel_layout --->%d\n", in_channel_layout);au_convert_ctx = swr_alloc();au_convert_ctx = swr_alloc_set_opts(au_convert_ctx, out_channel_layout, out_sample_fmt, out_sample_rate,in_channel_layout, pCodecCtx->sample_fmt, pCodecCtx->sample_rate, 0, NULL);swr_init(au_convert_ctx);SDL_PauseAudio(0);while (av_read_frame(pFormatCtx, packet) >= 0) {if (packet->stream_index == audioStream) {avcodec_send_packet(pCodecCtx, packet);while (avcodec_receive_frame(pCodecCtx, pFrame) == 0) {swr_convert(au_convert_ctx, &out_buffer, MAX_AUDIO_FRAME_SIZE, (const uint8_t**)pFrame->data,pFrame->nb_samples); // 转换音频}audio_chunk = (Uint8*)out_buffer;audio_len = out_buffer_size;audio_pos = audio_chunk;while (audio_len > 0) {SDL_Delay(1);//延迟播放}}av_packet_unref(packet);}swr_free(&au_convert_ctx);SDL_Quit();return 0;
}

在windows上,如果有方法废弃的错误,

错误    C4996    'AVCodecContext::channels': 被声明为已否决    

可以设置SDL检查为否,来解决

代码流程里,需要注意一下audio_callback是怎么回调的,

audio_callback函数是由SDL音频系统在需要更多音频数据以填充音频缓冲区时自动调用的。当SDL音频系统开始播放音频时,它会周期性地调用音频回调函数以获取新的音频数据。音频回调函数的调用频率取决于音频采样率和缓冲区大小。

main函数中,我们初始化SDL音频系统并设置了音频回调函数audio_callback

if (SDL_Init(SDL_INIT_AUDIO) < 0) {fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());exit(1);
}// 设置音频回调函数
SDL_AudioSpec desired;
desired.freq = audioCodecContext->sample_rate;
desired.format = AUDIO_S16SYS; // 使用16位有符号小端字节序样本
desired.channels = audioCodecContext->channels;
desired.samples = 4096; // 音频缓冲区大小,可以根据需要调整
desired.callback = audio_callback;
desired.userdata = NULL;// 打开音频设备
SDL_AudioDeviceID deviceId = SDL_OpenAudioDevice(NULL, 0, &desired, NULL, SDL_AUDIO_ALLOW_ANY_CHANGE);
if (deviceId <= 0) {fprintf(stderr, "Failed to open audio device: %s\n", SDL_GetError());return -1;
}// 开始播放音频
SDL_PauseAudioDevice(deviceId, 0);

当我们调用SDL_OpenAudioDevice函数时,SDL音频系统会注册音频回调函数audio_callback。当我们调用SDL_PauseAudioDevice(deviceId, 0)开始播放音频时,SDL音频系统会根据音频参数(如采样率、通道数和缓冲区大小)定期调用audio_callback函数。

audio_callback函数中,我们需要根据音频缓冲区的需求提供音频数据。这通常涉及从文件或实时流中解码音频数据,并将其传递给SDL音频系统。在我们的示例中,我们从全局变量audio_buffer中读取音频数据,该变量由swr_convert函数填充。

总之,audio_callback函数是由SDL音频系统在需要更多音频数据以填充音频缓冲区时自动触发的。您无需手动调用此函数,SDL音频系统会负责调用它。只需确保在回调函数中提供正确的音频数据即可。

这篇关于[FFmpeg学习]windows环境sdl播放音频试验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1068695

相关文章

基于Python开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

基于Linux的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

Windows的CMD窗口如何查看并杀死nginx进程

《Windows的CMD窗口如何查看并杀死nginx进程》:本文主要介绍Windows的CMD窗口如何查看并杀死nginx进程问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录Windows的CMD窗口查看并杀死nginx进程开启nginx查看nginx进程停止nginx服务

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061