My ffmpeg code. The output produced, with a WAV header for the sample rate of the original file, sounds like a sped up and distorted version of the original.
| #include <libavformat/avformat.h> | |
| #include <libavutil/samplefmt.h> | |
| #include <string.h> | |
| #include <stdio.h> | |
| const char* get_str_err(const int err) { | |
| static char buf[1024]; | |
| if (av_strerror(err, buf, sizeof(buf))) { | |
| strcpy(buf, "Couldn't get a proper error!"); | |
| } | |
| return buf; | |
| } | |
| int main(int argc, char **argv) { | |
| int err; | |
| av_register_all(); | |
| // setup format context | |
| AVFormatContext *fctx = NULL; | |
| if ((err = avformat_open_input(&fctx, argv[1], NULL, NULL)) < 0) { | |
| fprintf(stderr, "Couldn't open input: %s\n", get_str_err(err)); | |
| return err; | |
| } | |
| if ((err = avformat_find_stream_info(fctx, NULL)) < 0) { | |
| fprintf(stderr, "Couldn't find stream info: %s\n", get_str_err(err)); | |
| return err; | |
| } | |
| // find codec and stream ID | |
| AVCodec *codec = NULL; | |
| int stream_id = av_find_best_stream(fctx, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); | |
| fprintf(stderr, "Stream ID: %i\n", stream_id); | |
| AVStream *stream = NULL; | |
| stream = fctx->streams[stream_id]; | |
| AVCodecContext *codec_ctx = NULL; | |
| codec_ctx = stream->codec; | |
| // setup codec context | |
| if ((err = avcodec_open2(codec_ctx, codec, NULL)) < 0) { | |
| fprintf(stderr, "Couldn't open codec: %s\n", get_str_err(err)); | |
| return err; | |
| } | |
| AVFrame *frame = av_frame_alloc(); | |
| AVPacket packet; | |
| int got_frame = 0; | |
| // decode frames from file and output to stdout | |
| for (;;) { | |
| err = av_read_frame(fctx, &packet); | |
| if (err == 0xDFB9B0BB) {break;} // EOF | |
| if (packet.stream_index != stream_id) {continue;} | |
| int total_length = 0; | |
| for (;;) { | |
| int len = avcodec_decode_audio4(codec_ctx, frame, &got_frame, &packet); | |
| if (len == 0) {continue;} //skip if nothing was decoded | |
| if (got_frame) { | |
| int data_size = av_samples_get_buffer_size(NULL, codec_ctx->channels, frame->nb_samples, codec_ctx->sample_fmt, 1); | |
| fwrite(frame->data[0], 1, data_size, stdout); | |
| } | |
| total_length += len; | |
| if (total_length >= packet.size) { | |
| break; | |
| } | |
| } | |
| } | |
| //flush decoder | |
| for (;;) { | |
| packet.data = NULL; | |
| packet.size = 0; | |
| int len = avcodec_decode_audio4(codec_ctx, frame, &got_frame, &packet); | |
| if (len == 0) {break;} //nothing left | |
| if (got_frame) { | |
| int data_size = av_samples_get_buffer_size(NULL, codec_ctx->channels, frame->nb_samples, codec_ctx->sample_fmt, 1); | |
| fwrite(frame->data[0], 1, data_size, stdout); | |
| } | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment