写一个ffmpeg播放MP3的demo

时间: 2023-07-08 14:29:22 浏览: 46
这里提供一个简单的FFmpeg播放MP3的demo代码,你可以参考一下: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <libavutil/frame.h> #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswresample/swresample.h> #define AUDIO_BUF_SIZE (192000) AVFormatContext *pFormatCtx = NULL; AVCodecContext *pCodecCtx = NULL; AVCodec *pCodec = NULL; AVPacket *packet = NULL; AVFrame *frame = NULL; SwrContext *swrCtx = NULL; uint8_t *outBuffer = NULL; int audioIndex = -1; int ret = 0; pthread_t decodeThread; int quitFlag = 0; void *decode(void *arg) { while (!quitFlag) { if ((ret = av_read_frame(pFormatCtx, packet)) < 0) { break; } if (packet->stream_index == audioIndex) { if ((ret = avcodec_send_packet(pCodecCtx, packet)) < 0) { break; } while (ret >= 0) { ret = avcodec_receive_frame(pCodecCtx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { break; } else if (ret < 0) { break; } if (frame->channels > 0 && frame->channel_layout == 0) { frame->channel_layout = av_get_default_channel_layout(frame->channels); } else if (frame->channels == 0 && frame->channel_layout > 0) { frame->channels = av_get_channel_layout_nb_channels(frame->channel_layout); } int nbSamples = frame->nb_samples; int dataSize = av_samples_get_buffer_size(NULL, frame->channels, nbSamples, pCodecCtx->sample_fmt, 1); if (swrCtx) { swr_convert(swrCtx, &outBuffer, AUDIO_BUF_SIZE, (const uint8_t **)frame->data, nbSamples); dataSize = av_samples_get_buffer_size(NULL, pCodecCtx->channels, nbSamples, pCodecCtx->sample_fmt, 1); } else { outBuffer = frame->data[0]; } fwrite(outBuffer, 1, dataSize, stdout); } } av_packet_unref(packet); } return NULL; } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s input.mp3\n", argv[0]); return -1; } av_register_all(); avformat_network_init(); if ((ret = avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)) < 0) { printf("Failed to open input file: %s\n", argv[1]); return -1; } if ((ret = avformat_find_stream_info(pFormatCtx, NULL)) < 0) { printf("Failed to find stream info\n"); return -1; } for (int i = 0; i < pFormatCtx->nb_streams; i++) { if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { audioIndex = i; break; } } if (audioIndex == -1) { printf("Failed to find audio stream\n"); return -1; } pCodec = avcodec_find_decoder(pFormatCtx->streams[audioIndex]->codecpar->codec_id); if (!pCodec) { printf("Failed to find decoder for codec\n"); return -1; } pCodecCtx = avcodec_alloc_context3(pCodec); if (!pCodecCtx) { printf("Failed to allocate codec context\n"); return -1; } if ((ret = avcodec_parameters_to_context(pCodecCtx, pFormatCtx->streams[audioIndex]->codecpar)) < 0) { printf("Failed to copy codec parameters to codec context\n"); return -1; } if ((ret = avcodec_open2(pCodecCtx, pCodec, NULL)) < 0) { printf("Failed to open codec\n"); return -1; } packet = av_packet_alloc(); frame = av_frame_alloc(); if (!packet || !frame) { printf("Failed to allocate packet/frame\n"); return -1; } if (pCodecCtx->sample_fmt != AV_SAMPLE_FMT_S16) { swrCtx = swr_alloc_set_opts(NULL, av_get_default_channel_layout(pCodecCtx->channels), AV_SAMPLE_FMT_S16, pCodecCtx->sample_rate, av_get_default_channel_layout(pCodecCtx->channels), pCodecCtx->sample_fmt, pCodecCtx->sample_rate, 0, NULL); if (!swrCtx || swr_init(swrCtx) < 0) { printf("Failed to initialize resampling context\n"); return -1; } } outBuffer = (uint8_t *)av_malloc(AUDIO_BUF_SIZE); if (!outBuffer) { printf("Failed to allocate output buffer\n"); return -1; } pthread_create(&decodeThread, NULL, decode, NULL); pthread_detach(decodeThread); while (1) { usleep(1000); } quitFlag = 1; pthread_join(decodeThread, NULL); if (swrCtx) { swr_free(&swrCtx); } avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); av_packet_free(&packet); av_frame_free(&frame); if (outBuffer) { av_free(outBuffer); } return 0; } ``` 这个demo使用了FFmpeg来解码MP3音频文件,并将解码后的音频数据输出到标准输出。你可以通过将标准输出重定向到文件或者管道来实现保存或者传输音频数据。注意:这个demo并没有进行错误处理和异常退出处理,实际使用中需要根据需要进行修改。

相关推荐

最新推荐

recommend-type

使用 FFmpeg 命令拼接mp3音频文件异常问题及解决方法

主要介绍了使用 FFmpeg 命令拼接mp3音频文件异常问题及解决方法,本文给大家介绍的非常详细,对大家的工作或学习具有一定的参考借鉴价值,需要的朋友可以参考下
recommend-type

如何用FFmpeg编写一个简单播放器详细步骤介绍

通过一步一步的介绍怎么去调用ffmpeg和sdl的库,来编写一个简单的视频播放器,使自己了解整个过程。
recommend-type

python调用系统ffmpeg实现视频截图、http发送

主要为大家详细介绍了python调用系统ffmpeg实现视频截图、http发送,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a
recommend-type

matlab建立计算力学课程的笔记和文件.zip

matlab建立计算力学课程的笔记和文件.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。