The simplest ffmpeg-based audio encoder (PCM encoded as AAC)

Source: Internet
Author: User

This article describes one of the simplest audio encoders based on FFmpeg. The encoder realizes the PCM audio sample data encoded as AAC compressed encoded data. The encoder code is very simple, but each line of code is very important. By looking at the source code of this encoder. The ability to understand the FFmpeg audio encoding process.

This program uses the latest version of the class library (compile time is 2014.5.6). The development platform is VC2010. All the configuration is done, just need to execute it.


Process (2014.9.29 Update)

A flowchart with FFmpeg encoded audio is attached below.

Use this process. Not only can encode AAC audio, and can encode mp3,mp2 and so on various ffmpeg support audio. The function of the blue background in the figure is the function of the actual output data.

The light green function is the function of the audio encoding.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbgvpeglhb2h1ytewmja=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast "/>

Describe the meaning of each function in the process:

Av_register_all (): Register FFmpeg all codecs.

AVFORMAT_ALLOC_OUTPUT_CONTEXT2 (): Initializes the avformatcontext of the output stream.

Avio_open (): Open the output file.

Av_new_stream (): Creates the avstream of the output stream.

Avcodec_find_encoder (): Find the encoder.

Avcodec_open2 (): Open the encoder.

Avformat_write_header (): Write the file header (this function is not required for some package formats that do not have a file header.) Say Mpeg2ts).

Avcodec_encode_audio2 (): Encode audio. The Avframe (storage PCM sample data) is encoded as avpacket (stream data stored in the Aac,mp3 format).

Av_write_frame (): Writes the encoded video stream to the file.

Av_write_trailer (): Writes the end of the file (for some packaging formats that do not have a file header.) This function is not required. Say Mpeg2ts).


Code

/** * Simplest FFmpeg-based audio encoder *simplest FFmpeg Audio Encoder * * Lei Huawei Lei Xiaohua *[email protected] * Communication University/Digital TV technology *communication University of China/digital TV Technology *http://blog.csdn.net/leixiaohua1020 * * This program realizes the audio PCM sample data encoded as compressed stream (MP3. WMA,AAC, etc.).

The

* is the simplest tutorial for ffmpeg audio coding. * Learn the FFmpeg coding process by learning the sample.

*this software encode PCM data to AAC bitstream. *it ' s The simplest audio encoding software based on FFmpeg. *suitable for Beginner of FFmpeg * * #include <stdio.h> #define __STDC_CONSTANT_MACROS#IFDEF _win32//windowsextern " C "{#include" libavcodec/avcodec.h "#include" libavformat/avformat.h "}; #else//linux ... #ifdef __cplusplusextern" C "{# Endif#include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #ifdef __cplusplus}; #endif # Endifint Flush_encoder (avformatcontext *fmt_ctx,unsigned int stream_index) {int ret;int got_frame; Avpacket enc_pkt;if (!) ( Fmt_ctx->streams[stream_index]->codec->codec->capabilities &codec_cap_delay)) return 0;while (1) { Enc_pkt.data = Null;enc_pkt.size = 0;av_init_packet (&AMP;ENC_PKT); ret = Avcodec_encode_audio2 (fmt_ctx->streams[ Stream_index]->codec, &enc_pkt,null, &got_frame); Av_frame_free (NULL); if (Ret < 0) break;if (!got_frame) {ret=0;break;} printf ("Flush encoder:succeed to encode 1 frame!\tsize:%5d\n", ENC_PKT.size);/* MUX encoded frame */ret = Av_write_frame (Fmt_ctx, &AMP;ENC_PKT); if (Ret < 0) break;} return ret;} int main (int argc, char* argv[]) {avformatcontext* pformatctx; Avoutputformat* FMT; avstream* Audio_st; avcodeccontext* Pcodecctx; avcodec* pcodec;uint8_t* Frame_buf; Avframe* pframe; Avpacket pkt;int got_frame=0;int ret=0;int size=0; FILE *in_file=null; Raw PCM Dataint framenum=1000; Audio frame numberconst char* out_file = "TDJM.AAC"; Output urlint i;in_file= fopen ("TDJM.PCM", "RB"); Av_register_all ();//method 1.pFormatCtx = Avformat_alloc_context () FMT = Av_guess_format (null, out_file, null);p Formatctx->oformat = Fmt;//method 2.//avformat_alloc_output_context2 (&AMP;PFORMATCTX, NULL, NULL, out_file);//fmt = Pformatctx->oformat;//open output Urlif (Avio_open (&pformatctx- >pb,out_file, Avio_flag_read_write) < 0) {printf ("Failed to open output file!\n"); return-1;} Audio_st = Avformat_new_stream (pformatctx, 0);(Audio_st==null) {return-1;} Pcodecctx = audio_st->codec;pcodecctx->codec_id = Fmt->audio_codec;pcodecctx->codec_type = AVMEDIA_TYPE_ AUDIO;PCODECCTX-&GT;SAMPLE_FMT = av_sample_fmt_s16;pcodecctx->sample_rate= 44100;pcodecctx->channel_layout= Av_ch_layout_stereo;pcodecctx->channels = Av_get_channel_layout_nb_channels (pCodecCtx->channel_layout); Pcodecctx->bit_rate = 64000; Show some informationav_dump_format (pformatctx, 0, Out_file, 1);p codec = Avcodec_find_encoder (pcodecctx->codec_ ID) (!PCODEC) {printf ("Can not find encoder!\n"); return-1;} if (Avcodec_open2 (Pcodecctx, Pcodec,null) < 0) {printf ("Failed to open encoder!\n"); return-1;} Pframe = Av_frame_alloc ();p frame->nb_samples= pcodecctx->frame_size;pframe->format= PCodecCtx->sample_ Fmt;size = Av_samples_get_buffer_size (NULL, Pcodecctx->channels,pcodecctx->frame_size,pcodecctx->sample_ FMT, 1); frame_buf = (uint8_t *) av_malloc (size); Avcodec_fill_audio_frame (Pframe, Pcodecctx->channEls, PCODECCTX-&GT;SAMPLE_FMT, (const uint8_t*) frame_buf, size, 1);//write Headeravformat_write_header (PFormatCtx, NULL); Av_new_packet (&pkt,size); for (i=0; i<framenum; i++) {//read pcmif (fread (frame_buf, 1, size, in_file) <= 0) {printf ("Failed to read Raw data! \ n "); return-1;} else if (feof (In_file)) {break;} Pframe->data[0] = frame_buf; PCM Datapframe->pts=i*100;got_frame=0;//encoderet = Avcodec_encode_audio2 (Pcodecctx, &pkt,pFrame, &got _frame); if (Ret < 0) {printf ("Failed to encode!\n"); return-1;} if (got_frame==1) {printf ("Succeed to encode 1 frame! \tsize:%5d\n ", pkt.size);p kt.stream_index = Audio_st->index;ret = Av_write_frame (Pformatctx, &pkt); av_free_ Packet (&AMP;PKT);}} Flush Encoderret = Flush_encoder (pformatctx,0), if (Ret < 0) {printf ("Flushing encoder failed\n"); return-1;} Write Trailerav_write_trailer (PFORMATCTX);//cleanif (Audio_st) {avcodec_close (AUDIO_ST-&GT;CODEC); Av_free ( pframe); Av_free (FRAME_BUF);} Avio_close (PFORMATCTX-&GT;PB); avformat_fRee_context (PFORMATCTX); fclose (in_file); return 0;}



Results

After execution of the program is complete. A PCM sample data file (*.PCM) is encoded as an AAC stream file (*.AAC).


Download

Simplest FFmpeg Audio encoder


Project Home

sourceforge:https://sourceforge.net/projects/simplestffmpegaudioencoder/

Github:https://github.com/leixiaohua1020/simplest_ffmpeg_audio_encoder

Open source China: Http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_audio_encoder


Csdnproject:

http://download.csdn.net/detail/leixiaohua1020/7324091

Pudnproject:

Http://www.pudn.com/downloads644/sourcecode/multimedia/detail2605236.html


Updated-1.1 (2015.2.13) =========================================

This time considering the cross-platform requirements, adjusted the source code. After this adjustment, the source code can be compiled on the following platform:

VC + +: Open the SLn file to compile without configuration.

Cl.exe: Open Compile_cl.bat can be used to compile the command line under the cl.exe, note that you may need to follow the VC installation path to adjust the number of parameters in the script. Compile commands such as the following.

:: VS2010 environmentcall "D:\Program Files\Microsoft Visual Studio 10.0\vc\vcvarsall.bat":: Include@set include= Include;%i Nclude%::lib@set Lib=lib;%lib%::compile and Linkcl simplest_ffmpeg_audio_encoder.cpp/link avcodec.lib avformat.lib Avutil.lib ^avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib/opt:noref

The MINGW:MINGW command-line execution compile_mingw.sh can be compiled using MinGW's g++.

Compile commands such as the following.

g++ simplest_ffmpeg_audio_encoder.cpp-g-o simplest_ffmpeg_audio_encoder.exe-i/usr/local/include-l/usr/local/lib- Lavformat-lavcodec-lavutil

Gcc:linux or MacOS command line execution compile_gcc.sh can be compiled using GCC. Compile commands such as the following.

GCC simplest_ffmpeg_audio_encoder.cpp-g-o simplest_ffmpeg_audio_encoder.out-i/usr/local/include-l/usr/local/lib- Lavformat-lavcodec-lavutil

PS: Related compilation commands have been saved in the project directory


csdn:http://download.csdn.net/detail/leixiaohua1020/8445209

The SourceForge has been updated.


The simplest ffmpeg-based audio encoder (PCM encoded as AAC)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.