- #include <stdio.h>
- #include <stdlib.h>
- #include <libavcodec/avcodec.h>
- #include <libavformat/avformat.h>
- #include <libavutil/avutil.h>
- #include <alsa/asoundlib.h>
- void
- die(char *why)
- {
- }
- int
- main(int argc, char *argv[])
- {
- if (argc < 2)
- die("argc");
- snd_pcm_t *handle;
- if (snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0)
- die("snd_pcm_open");
- struct AVFormatContext *formatContext;
- if (avformat_open_input(&formatContext, argv[1], NULL, NULL) < 0)
- die("avformat_open_input");
- if (avformat_find_stream_info(formatContext, NULL) < 0) {
- die("avformat_find_stream_info");
- }
- int streamId = -1;
- streamId = av_find_best_stream(formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
- if (streamId == -1)
- die("streamId");
- const struct AVCodec *codec = avcodec_find_decoder(formatContext->streams[streamId]->codecpar->codec_id);
- struct AVCodecContext *codecContext = avcodec_alloc_context3(codec);
- if (avcodec_parameters_to_context(codecContext, formatContext->streams[streamId]->codecpar)) {
- avcodec_free_context(&codecContext);
- die("avcodec_parameters_to_context");
- }
- if (avcodec_open2(codecContext, codec, NULL) < 0) {
- avcodec_free_context(&codecContext);
- die("avcodec_open2");
- }
- snd_pcm_set_params(handle,
- SND_PCM_FORMAT_S16_LE,
- SND_PCM_ACCESS_RW_INTERLEAVED,
- formatContext->streams[streamId]->codecpar->ch_layout.nb_channels,
- codecContext->sample_rate,
- 1, 500000);
- AVPacket *packet = av_packet_alloc();
- AVFrame *frame = av_frame_alloc();
- while (av_read_frame(formatContext, packet) >= 0)
- {
- if (avcodec_send_packet(codecContext, packet) != 0)
- break;
- while (!avcodec_receive_frame(codecContext, frame))
- {
- void *audio_data = frame->data[0];
- snd_pcm_sframes_t frames = frame->nb_samples;
- while (frames > 0)
- {
- snd_pcm_sframes_t written = snd_pcm_writei(handle, audio_data, frames);
- if (written < 0) {
- break;
- } else {
- frames -= written;
- audio_data += written * av_get_bytes_per_sample(frame->format) * formatContext->streams[streamId]->codecpar->ch_layout.nb_channels;
- }
- if (written < 0 && written != -EAGAIN)
- goto end_playback;
- }
- int16_t *samples = (int16_t *)frame->data[0];
- for (int i = 0; i < frame->nb_samples; i++)
- }
- av_packet_unref(packet);
- }
- end_playback:
- av_packet_free(&packet);
- av_frame_free(&frame);
- avcodec_free_context(&codecContext);
- avformat_close_input(&formatContext);
- snd_pcm_close(handle);
- return 0;
- }
ffmpeg examepl
Posted by Anonymous on Fri 15th Aug 2025 21:55
raw | new post
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.