1. #include <stdio.h>
    2. #define __STDC_CONSTANT_MACROS
    3. #ifdef _WIN32
    4. extern "C"{
    5. #include "libavformat/avformat.h"
    6. };
    7. #else
    8. #ifdef __cplusplus
    9. extern "C"{
    10. #endif
    11. #include <libavformat/avformat.h>
    12. #ifdef __cplusplus
    13. };
    14. #endif
    15. #endif
    16. int main(int argc, char* argv[]){
    17. AVFormatContext *ifmt_ctx = NULL;
    18. AVPacket pkt;
    19. int ret, i;
    20. int videoindex = -1, audioindex = -1;
    21. const char *in_filename = "in.flv";
    22. const char *out_filename_v = "out.h264";
    23. const char *out_filename_a = "out.mp3";
    24. av_register_all();
    25. if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
    26. printf("Could not open input file.");
    27. return -1;
    28. }
    29. if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
    30. printf("Failed to retrieve input stream information");
    31. return -1;
    32. }
    33. videoindex = -1;
    34. for (i = 0; i<ifmt_ctx->nb_streams; i++) {
    35. if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
    36. videoindex = i;
    37. }
    38. else if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
    39. audioindex = i;
    40. }
    41. }
    42. printf("===========================\Input Video===========================\n");
    43. av_dump_format(ifmt_ctx, 0, in_filename, 0);
    44. printf("==================================================================\n");
    45. FILE *fp_audio = fopen(out_filename_a, "wb+");
    46. FILE *fp_video = fopen(out_filename_v, "wb+");
    47. while (av_read_frame(ifmt_ctx, &pkt) >= 0) {
    48. if (pkt.stream_index == videoindex) {
    49. printf("Write Video Packet. size:%d\tpts:%lld\n", pkt.size, pkt.pts);
    50. fwrite(pkt.data, 1, pkt.size, fp_video);
    51. }
    52. else if (pkt.stream_index == audioindex) {
    53. /*注意:FLV/MP4/MKV等格式中的AAC码流(上述封装格式中的AAC的AVPacket中的数据缺失了7字节的ADTS文件头)*/
    54. printf("Write Audio Packet. size:%d\tpts:%lld\n", pkt.size, pkt.pts);
    55. fwrite(pkt.data, 1, pkt.size, fp_audio);
    56. }
    57. av_free_packet(&pkt);
    58. }
    59. fclose(fp_video);
    60. fclose(fp_audio);
    61. avformat_close_input(&ifmt_ctx);
    62. if (ret < 0 && ret != AVERROR_EOF) {
    63. printf("Error occurred.\n");
    64. return -1;
    65. }
    66. return 0;
    67. }

    qrcode_for_gh_e95b474fcf08_344.jpg