How to extract audio form video using ffmpeg in C++?

1.2k Views Asked by At

I'm developing a C++ app that uses FFmpeg to play audio/video. Now I want to enhance the application to allow the users to extract audio from video. How can FFmpeg can be used for this? I searched a lot about this but I was not able to find a tutorial regarding it.

2

There are 2 best solutions below

2
On

This seems like a simple scripting task... why do you want to use the heavy artillery (C/C++) to swat a fly?

I use Applescript to build/run an ffmpeg command line via a Bash shell. The only reason I involve Applescript is so I can invoke it as a droplet (ie drag-and-drop the file(s) onto the app and have it run without interaction.)

I get that you're probably on Windows, meaning no Applescript and no Bash. But surely something lighter than C can build/run an ffmpeg command line. It's really as simple as:

ffmpeg -i infile.mp4 -b 160k outfile.mp3
4
On

You need to

  1. Open the input context [ avformat_open_input ]
  2. Get the stream information [ avformat_find_stream_info ]
  3. Get the audio stream:
if (inputFormatContext->streams[index]->codec->codec_type ==
    AVMEDIA_TYPE_AUDIO) {
  inputAudioStream = inputFormatContext->streams[index];
}
  1. Read each packet. AVPacket packet;
int ret = av_read_frame(inputFormatContext, &packet);
if (ret == 0) {
  if (packet.stream_index == inputAudioStream->index) {
    // packet.data will have encoded audio data.
  }
}