Simplest FFMPEG+SDL-based audio player: split-decoder and player

Source: Internet
Author: User
Tags fread

This article complements the two examples in the simplest ffmpeg+sdl-based audio player: The FFmpeg audio decoder and the SDL audio sampling data player. These two sections are the two examples that are split out from the audio player. The FFmpeg audio decoder enables the decoding of video data to PCM sampled data, while the SDL audio sampling data player enables the playback of PCM data to audio devices. In short, the original FFMPEG+SDL audio player was implemented:

Audio Data->pcm-> Audio Devices

The FFmpeg audio decoder implements:

Audio Data->PCM

The SDL audio sampling data player implements:

pcm-> Audio Device
FFmpeg Audio Decoder Source code
/** * Simplest FFmpeg based audio decoder * Simplest FFMPEG audio Decoder * * Lei hua Lei Xiaohua * [email protected] * Communication University/Digital TV Technology * Co Mmunication University of China/digital TV technology * http://blog.csdn.net/leixiaohua1020 * * This program can decode the audio stream (MP3,AAC, etc.) to P CM sampled data. * Is the simplest ffmpeg audio decoding aspect of the tutorial. * Learn this example to understand the decoding process of ffmpeg. * * This software decode audio streams (Aac,mp3 ...) to PCM data. * Suitable for beginner of FFmpeg. * */#include <stdio.h> #include <stdlib.h> #include <string.h> #define __STDC_CONSTANT_MACROS#IFDEF _ Win32//windowsextern "C" {#include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "libswresample/ Swresample.h "}; #else//linux ... #ifdef __cplusplusextern" C "{#endif # include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswresample/swresample.h> #ifdef __cplusplus}; #endif #endif#define Max_audio_frame_size 192000//1 second of 48khz 32bit audioint main (int argc, char* argv[]) {avformatcontext*pformatctx;in TI, Audiostream; AvcodeCcontext*pcodecctx; Avcodec*pcodec; Avpacket*packet;uint8_t*out_buffer;    Avframe*pframe; int ret;uint32_t len = 0;int Got_picture;int index = 0;int64_t in_channel_layout;struct swrcontext *au_convert_ctx; FILE *pfile=fopen ("OUTPUT.PCM", "WB"), char url[]= "Skycity1.mp3"; Av_register_all (); Avformat_network_init (); Pformatctx = Avformat_alloc_context ();//openif (Avformat_open_input (&pformatctx,url,null,null)!=0) {printf (" Couldn ' t open input stream.\n "); return-1;} Retrieve Stream informationif (Avformat_find_stream_info (pformatctx,null) <0) {printf ("couldn ' t find stream Information.\n "); return-1;} Dump valid information onto standard Errorav_dump_format (pformatctx, 0, URL, false);//Find the first audio Streamaudio Stream=-1;for (i=0; i < pformatctx->nb_streams; i++) if (pformatctx->streams[i]->codec->codec_type== Avmedia_type_audio) {audiostream=i;break;} if (audiostream==-1) {printf ("didn ' t find a audio stream.\n"); return-1;} Get A pointer to the codec context for the audio streampcodecctx=pformatctx->streams[audiostream]->codec;//Find The decoder for the audio streampcodec=avcodec_ Find_decoder (pcodecctx->codec_id); if (pcodec==null) {printf ("Codec not found.\n"); return-1;} Open Codecif (Avcodec_open2 (Pcodecctx, Pcodec,null) <0) {printf ("Could not open codec.\n"); return-1;} packet= (Avpacket *) av_malloc (sizeof (Avpacket)); Av_init_packet (packet);//out Audio paramuint64_t out_channel_layout =av_ch_layout_stereo;//nb_samples:aac-1024 Mp3-1152int out_nb_samples=pcodecctx->frame_size; Avsampleformat Out_sample_fmt=av_sample_fmt_s16;int Out_sample_rate=44100;int Out_channels=av_get_channel_layout_ Nb_channels (out_channel_layout);//out Buffer sizeint 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);p Frame=av_frame_alloc ();//fix:some Codec ' s Context information is missingin_channel_layout=av_get_default_channel_layout (pCodecCtx-> Channels);//swrau_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-&GT;SAMPLE_FMT, pcodecctx->sample_rate,0, NULL); Swr_init (Au_convert_ CTX); while (Av_read_frame (pformatctx, packet) >=0) {if (packet->stream_index==audiostream) {ret = Avcodec_decode _audio4 (Pcodecctx, pframe,&got_picture, packet); if (Ret < 0) {printf ("Error in decoding audio fr                Ame.\n ");            return-1; }if (Got_picture > 0) {swr_convert (Au_convert_ctx,&out_buffer, Max_audio_frame_size, (const uint8_t * *) pFrame- >data, Pframe->nb_samples);p rintf ("index:%5d\t pts:%lld\t packet size:%d\n",index,packet->pts,packet-> size);//write pcmfwrite (Out_buffer, 1, out_buffer_size, pFile); index++;}} Av_free_packet (packet);} Swr_free (&AMP;AU_CONVERT_CTX); fclose (pFile); Av_free (out_buffer);//Close the Codecavcodec_close (PCODECCTX);// Close the video fileavformat_close_input (&pformatctx); return 0;} 

After running the resulting program, the following audio files are decoded.
The decoded PCM sample data is saved as a file. You can view the contents of the PCM after you set up the sample rate with Adobe Audition.

SDL Audio Sample data player source code
/** * Simplest SDL2 Play audio example (SDL2 playback PCM) * Simplest audio play SDL2 (SDL2 play PCM) * * Lei hua Lei Xiaohua * [email protected] * Communication University/Digital TV Technology * Communication University of China/digital TV Technology * HTTP://BLOG.CSDN.NET/LEIXIAOHUA1020 * * This program enables Use SDL2 to play PCM audio sampling data. SDL is actually an encapsulation of the underlying drawing * API (DIRECT3D,OPENGL), which is significantly easier to use than calling the underlying * API directly. * * Function call steps are as follows: * * [Initialize] * SDL_INIT (): Initialize SDL. * Sdl_openaudio (): Open the audio device according to the parameters (stored in sdl_audiospec). * * [Looping data] * Sdl_pauseaudio (): Play audio data. * Sdl_delay (): Delay waiting for playback to complete. * * This software plays PCM raw audio data using SDL2. * SDL is a wrapper of low-level API (DirectSound). * Use of SDL is much easier than directly call these low-level API. * The process is shown as follows: * * [init] * SDL_INIT (): Init SDL. * Sdl_openaudio (): Opens the audio device with the desired *parameters (in Sdl_audiospec). * * [Loop to play data] * Sdl_pauseaudio (): Play Audio. * Sdl_delay (): Wait for completetion of playback. */#include <stdio.h> #include <tchar.h>extern "C" {#include "sdl/sdl.h "};//buffer://|-----------|-------------|//chunk-------POS---len-----|static Uint8 *audio_chunk; Static Uint32 Audio_len; Static Uint8 *audio_pos; /* Audio Callback * The audio function Callback takes the following parameters: * stream:a pointer to the audio buffer T o be filled * len:the length (in bytes) of the audio buffer * */void Fill_audio (void *udata,uint8 *stream,int len) {/ /SDL 2.0sdl_memset (stream, 0, Len), if (audio_len==0)/* Only play if we had data left */return; Len= (Len>audio_len?audio_len:len);/* Mix as much data as possible */Sdl_mixaudio (stream,audio_pos,len,sdl_mix_m Axvolume); Audio_pos + = Len; Audio_len-= Len; } int main (int argc, char* argv[]) {//initif (Sdl_init | Sdl_init_timer) {printf ("Could not initialize SDL-%s\n", Sdl_geterror ()); return-1;} Sdl_audiospecsdl_audiospec wanted_spec;wanted_spec.freq = 44100; Wanted_spec.format = Audio_s16sys; Wanted_spec.channels = 2; wanted_spec.silence = 0; Wanted_spec. samples = 1024; Wanted_spec.callback = Fill_audio; if (Sdl_openaudio (&wanted_spec, NULL) <0) {printf ("can ' t open audio.\n"); return-1;} FILE *fp=fopen ("NOCTURNENO2INEFLAT_44.1K_S16LE.PCM", "rb+"), if (fp==null) {printf ("Cannot open this file\n"); return-1 ;} For Yuv420pint Pcm_buffer_size=4096;char *pcm_buffer= (char *) malloc (pcm_buffer_size); int Data_count=0;while (1) {if (Fread (Pcm_buffer, 1, pcm_buffer_size, fp)! = pcm_buffer_size) {//Loopfseek (FP, 0, Seek_set); Fread (Pcm_buffer, 1, pcm_buffer_size, FP);d ata_count=0;} printf ("Now Playing%10d Bytes data.\n", Data_count);d ata_count+=pcm_buffer_size;//set Audio buffer (PCM data) Audio_ Chunk = (Uint8 *) Pcm_buffer; Audio buffer Lengthaudio_len =pcm_buffer_size;audio_pos = audio_chunk;//playsdl_pauseaudio (0); while (audio_len> 0)//wait until Finishsdl_delay (1); }free (Pcm_buffer); Sdl_quit (); return 0;}

After running the result program, a PCM sample data file under the program folder is read, as shown below.
The PCM data is then output to the system's audio device (audio, headphones).

Download
simplest FFmpeg Audio Player

sourceforge:https://sourceforge.net/projects/simplestffmpegaudioplayer/

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

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


This program realizes the decoding and playback of audio. Is the simplest ffmpeg audio decoding aspect of the tutorial.
You can learn about the decoding process of ffmpeg by studying this example.
The project consists of 3 projects:
Simplest_ffmpeg_audio_player: FFMPEG+SDL-based audio decoder
Simplest_ffmpeg_audio_decoder: Audio decoder. Libavcodec and Libavformat are used.
SIMPLEST_AUDIO_PLAY_SDL2: Example of using SDL2 to play PCM sampled data.





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Simplest FFMPEG+SDL-based audio player: split-decoder and player

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.