Winui3 FFmpeg.autogen 解析音频,使用NAudio播放;

打印 上一主题 下一主题

主题 890|帖子 890|积分 2670

     在上两篇文章中已经将播放视频的功能实现了,今天我就来讲解一下如何通过FFmpeg来解析音频内容,并且用NAudio来进行音频播放;
     效果图
     虽然效果图是gif并不能
 
听到音频播放的内容,不过可以从图中看到已经是实现了音频的播放,暂停,停止已经更改进度的内容了;
一。添加NAudio库:
  
一.音频解码播放流程
   可以从流程图中看到音频的解码跟视频的解码是差不多的,只有是重采样跟将帧数据转换成字节数组这两个步骤有区别而已。
  1.初始化音频解码
  1. public void InitDecodecAudio(string path)
  2.         {
  3.             int error = 0;
  4.             //创建一个 媒体格式上下文
  5.             format = ffmpeg.avformat_alloc_context();
  6.             var tempFormat = format;
  7.             //打开媒体文件
  8.             error = ffmpeg.avformat_open_input(&tempFormat, path, null, null);
  9.             if (error < 0)
  10.             {
  11.                 Debug.WriteLine("打开媒体文件失败");
  12.                 return;
  13.             }
  14.             //嗅探媒体信息
  15.             ffmpeg.avformat_find_stream_info(format, null);
  16.             AVCodec* codec;
  17.             //获取音频流索引
  18.             audioStreamIndex = ffmpeg.av_find_best_stream(format, AVMediaType.AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
  19.             if (audioStreamIndex < 0)
  20.             {
  21.                 Debug.WriteLine("没有找到音频流");
  22.                 return;
  23.             }
  24.             //获取音频流
  25.             audioStream = format->streams[audioStreamIndex];
  26.             //创建解码上下文
  27.             codecContext = ffmpeg.avcodec_alloc_context3(codec);
  28.             //将音频流里面的解码器参数设置到 解码器上下文中
  29.             error = ffmpeg.avcodec_parameters_to_context(codecContext, audioStream->codecpar);
  30.             if (error < 0)
  31.             {
  32.                 Debug.WriteLine("设置解码器参数失败");
  33.             }
  34.             error = ffmpeg.avcodec_open2(codecContext, codec, null);
  35.             //媒体时长
  36.             Duration = TimeSpan.FromMilliseconds(format->duration / 1000);
  37.             //编解码id
  38.             CodecId = codec->id.ToString();
  39.             //解码器名字
  40.             CodecName = ffmpeg.avcodec_get_name(codec->id);
  41.             //比特率
  42.             Bitrate = codecContext->bit_rate;
  43.             //音频通道数
  44.             Channels = codecContext->channels;
  45.             //通道布局类型
  46.             ChannelLyaout = codecContext->channel_layout;
  47.             //音频采样率
  48.             SampleRate = codecContext->sample_rate;
  49.             //音频采样格式
  50.             SampleFormat = codecContext->sample_fmt;
  51.             //采样次数  //获取给定音频参数所需的缓冲区大小。
  52.             BitsPerSample = ffmpeg.av_samples_get_buffer_size(null, 2, codecContext->frame_size, AVSampleFormat.AV_SAMPLE_FMT_S16, 1);
  53.             //创建一个指针
  54.             audioBuffer = Marshal.AllocHGlobal((int)BitsPerSample);
  55.             bufferPtr = (byte*)audioBuffer;
  56.             //初始化音频重采样转换器
  57.             InitConvert((int)ChannelLyaout, AVSampleFormat.AV_SAMPLE_FMT_S16, (int)SampleRate, (int)ChannelLyaout, SampleFormat, (int)SampleRate);
  58.             //创建一个包和帧指针
  59.             packet = ffmpeg.av_packet_alloc();
  60.             frame = ffmpeg.av_frame_alloc();
  61.             State = MediaState.Read;
  62.         }
复制代码
InitDecodecAudio   在初始化各个结构的代码其实是跟解码视频的流程差不多的,只是获取媒体流的类型从视频类型更改成了音频类型,和媒体的信息从视频改为了音频信息,并且获取了音频的采样次数和创建了一个用于后续读取音频数据的指针。
  2.初始化音频重采样转换器。
  1. /// <summary>
  2.         /// 初始化重采样转换器
  3.         /// </summary>
  4.         /// <param name="occ">输出的通道类型</param>
  5.         /// <param name="osf">输出的采样格式</param>
  6.         /// <param name="osr">输出的采样率</param>
  7.         /// <param name="icc">输入的通道类型</param>
  8.         /// <param name="isf">输入的采样格式</param>
  9.         /// <param name="isr">输入的采样率</param>
  10.         /// <returns></returns>
  11.         bool InitConvert(int occ, AVSampleFormat osf, int osr, int icc, AVSampleFormat isf, int isr)
  12.         {
  13.             //创建一个重采样转换器
  14.             convert = ffmpeg.swr_alloc();
  15.             //设置重采样转换器参数
  16.             convert = ffmpeg.swr_alloc_set_opts(convert, occ, osf, osr, icc, isf, isr, 0, null);
  17.             if (convert == null)
  18.                 return false;
  19.             //初始化重采样转换器
  20.             ffmpeg.swr_init(convert);
  21.             return true;
  22.         }
复制代码
InitConvert     根据输入参数初始化了一个 SwrContext结构的音频转换器,跟 视频的SwsContext结构是不同的。
  3。从音频帧读取数据。
  1. public byte[] FrameConvertBytes(AVFrame* sourceFrame)
  2.         {
  3.             var tempBufferPtr = bufferPtr;
  4.             //重采样音频
  5.             var outputSamplesPerChannel = ffmpeg.swr_convert(convert, &tempBufferPtr, frame->nb_samples, sourceFrame->extended_data, sourceFrame->nb_samples);
  6.             //获取重采样后的音频数据大小
  7.             var outPutBufferLength = ffmpeg.av_samples_get_buffer_size(null, 2, outputSamplesPerChannel, AVSampleFormat.AV_SAMPLE_FMT_S16, 1);
  8.             if (outputSamplesPerChannel < 0)
  9.                 return null;
  10.             byte[] bytes = new byte[outPutBufferLength];
  11.             //从内存中读取转换后的音频数据
  12.             Marshal.Copy(audioBuffer, bytes, 0, bytes.Length);
  13.             return bytes;
  14.         }
复制代码
FrameConvertBytes      调用ffmpeg.swr_convert()将音频帧通过重采样后音频的数据大小会发生改变的,需要再次调用 ffmpeg.av_samples_get_buffer_size() 来重新计算 音频数据大小,并通过指针位置获取数据;
     4.声明音频播放组件
  1. //NAudio音频播放组件
  2.         private WaveOut waveOut;
  3.         private BufferedWaveProvider bufferedWaveProvider;
复制代码
  5.在线程任务上循环读取音频帧解码成字节数组并 向bufferedAveProvider 添加音频样本,当添加的音频数据大于预设的数据量则将缓存内的数据都清除掉。
  1.     PlayTask = new Task(() =>            {                while (true)                {                    //播放中                    if (audio.IsPlaying)                    {                        //获取下一帧视频                        if (audio.TryReadNextFrame(out var frame))                        {                            var bytes = audio.FrameConvertBytes(&frame);                            if (bytes == null)                                continue;                            if (bufferedWaveProvider.BufferLength  OffsetClock + clock.Elapsed; }        ///         /// 解码器名字        ///         public string CodecName { get; protected set; }        ///         /// 解码器Id        ///         public string CodecId { get; protected set; }        ///         /// 比特率        ///         public long Bitrate { get; protected set; }        //通道数        public int Channels { get; protected set; }        //采样率        public long SampleRate { get; protected set; }        //采样次数        public long BitsPerSample { get; protected set; }        //通道布局        public ulong ChannelLyaout { get; protected set; }        ///         /// 采样格式        ///         public AVSampleFormat SampleFormat { get; protected set; }        public void InitDecodecAudio(string path)
  2.         {
  3.             int error = 0;
  4.             //创建一个 媒体格式上下文
  5.             format = ffmpeg.avformat_alloc_context();
  6.             var tempFormat = format;
  7.             //打开媒体文件
  8.             error = ffmpeg.avformat_open_input(&tempFormat, path, null, null);
  9.             if (error < 0)
  10.             {
  11.                 Debug.WriteLine("打开媒体文件失败");
  12.                 return;
  13.             }
  14.             //嗅探媒体信息
  15.             ffmpeg.avformat_find_stream_info(format, null);
  16.             AVCodec* codec;
  17.             //获取音频流索引
  18.             audioStreamIndex = ffmpeg.av_find_best_stream(format, AVMediaType.AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
  19.             if (audioStreamIndex < 0)
  20.             {
  21.                 Debug.WriteLine("没有找到音频流");
  22.                 return;
  23.             }
  24.             //获取音频流
  25.             audioStream = format->streams[audioStreamIndex];
  26.             //创建解码上下文
  27.             codecContext = ffmpeg.avcodec_alloc_context3(codec);
  28.             //将音频流里面的解码器参数设置到 解码器上下文中
  29.             error = ffmpeg.avcodec_parameters_to_context(codecContext, audioStream->codecpar);
  30.             if (error < 0)
  31.             {
  32.                 Debug.WriteLine("设置解码器参数失败");
  33.             }
  34.             error = ffmpeg.avcodec_open2(codecContext, codec, null);
  35.             //媒体时长
  36.             Duration = TimeSpan.FromMilliseconds(format->duration / 1000);
  37.             //编解码id
  38.             CodecId = codec->id.ToString();
  39.             //解码器名字
  40.             CodecName = ffmpeg.avcodec_get_name(codec->id);
  41.             //比特率
  42.             Bitrate = codecContext->bit_rate;
  43.             //音频通道数
  44.             Channels = codecContext->channels;
  45.             //通道布局类型
  46.             ChannelLyaout = codecContext->channel_layout;
  47.             //音频采样率
  48.             SampleRate = codecContext->sample_rate;
  49.             //音频采样格式
  50.             SampleFormat = codecContext->sample_fmt;
  51.             //采样次数  //获取给定音频参数所需的缓冲区大小。
  52.             BitsPerSample = ffmpeg.av_samples_get_buffer_size(null, 2, codecContext->frame_size, AVSampleFormat.AV_SAMPLE_FMT_S16, 1);
  53.             //创建一个指针
  54.             audioBuffer = Marshal.AllocHGlobal((int)BitsPerSample);
  55.             bufferPtr = (byte*)audioBuffer;
  56.             //初始化音频重采样转换器
  57.             InitConvert((int)ChannelLyaout, AVSampleFormat.AV_SAMPLE_FMT_S16, (int)SampleRate, (int)ChannelLyaout, SampleFormat, (int)SampleRate);
  58.             //创建一个包和帧指针
  59.             packet = ffmpeg.av_packet_alloc();
  60.             frame = ffmpeg.av_frame_alloc();
  61.             State = MediaState.Read;
  62.         }        //缓冲区指针        IntPtr audioBuffer;        //缓冲区句柄        byte* bufferPtr;        /// <summary>
  63.         /// 初始化重采样转换器
  64.         /// </summary>
  65.         /// <param name="occ">输出的通道类型</param>
  66.         /// <param name="osf">输出的采样格式</param>
  67.         /// <param name="osr">输出的采样率</param>
  68.         /// <param name="icc">输入的通道类型</param>
  69.         /// <param name="isf">输入的采样格式</param>
  70.         /// <param name="isr">输入的采样率</param>
  71.         /// <returns></returns>
  72.         bool InitConvert(int occ, AVSampleFormat osf, int osr, int icc, AVSampleFormat isf, int isr)
  73.         {
  74.             //创建一个重采样转换器
  75.             convert = ffmpeg.swr_alloc();
  76.             //设置重采样转换器参数
  77.             convert = ffmpeg.swr_alloc_set_opts(convert, occ, osf, osr, icc, isf, isr, 0, null);
  78.             if (convert == null)
  79.                 return false;
  80.             //初始化重采样转换器
  81.             ffmpeg.swr_init(convert);
  82.             return true;
  83.         }        ///         /// 尝试读取下一帧        ///         ///         ///         public bool TryReadNextFrame(out AVFrame outFrame)        {            if (lastTime == TimeSpan.Zero)            {                lastTime = Position;                isNextFrame = true;            }            else            {                if (Position - lastTime >= frameDuration)                {                    lastTime = Position;                    isNextFrame = true;                }                else                {                    outFrame = *frame;                    return false;                }            }            if (isNextFrame)            {                lock (SyncLock)                {                    int result = -1;                    //清理上一帧的数据                    ffmpeg.av_frame_unref(frame);                    while (true)                    {                        //清理上一帧的数据包                        ffmpeg.av_packet_unref(packet);                        //读取下一帧,返回一个int 查看读取数据包的状态                        result = ffmpeg.av_read_frame(format, packet);                        //读取了最后一帧了,没有数据了,退出读取帧                        if (result == ffmpeg.AVERROR_EOF || result < 0)                        {                            outFrame = *frame;                            StopPlay();                            return false;                        }                        //判断读取的帧数据是否是视频数据,不是则继续读取                        if (packet->stream_index != audioStreamIndex)                            continue;                        //将包数据发送给解码器解码                        ffmpeg.avcodec_send_packet(codecContext, packet);                        //从解码器中接收解码后的帧                        result = ffmpeg.avcodec_receive_frame(codecContext, frame);                        if (result < 0)                            continue;                        //计算当前帧播放的时长                        frameDuration = TimeSpan.FromTicks((long)Math.Round(TimeSpan.TicksPerMillisecond * 1000d * frame->nb_samples / frame->sample_rate, 0));                        outFrame = *frame;                        return true;                    }                }            }            else            {                outFrame = *frame;                return false;            }        }        void StopPlay()        {            lock (SyncLock)            {                if (State == MediaState.None) return;                IsPlaying = false;                OffsetClock = TimeSpan.FromSeconds(0);                clock.Reset();                clock.Stop();                var tempFormat = format;                ffmpeg.avformat_free_context(tempFormat);                format = null;                var tempCodecContext = codecContext;                ffmpeg.avcodec_free_context(&tempCodecContext);                var tempPacket = packet;                ffmpeg.av_packet_free(&tempPacket);                var tempFrame = frame;                ffmpeg.av_frame_free(&tempFrame);                var tempConvert = convert;                ffmpeg.swr_free(&tempConvert);                Marshal.FreeHGlobal(audioBuffer);                bufferPtr = null;                audioStream = null;                audioStreamIndex = -1;                //视频时长                Duration = TimeSpan.FromMilliseconds(0);                //编解码器名字                CodecName = String.Empty;                CodecId = String.Empty;                //比特率                Bitrate = 0;                //帧率                              Channels = 0;                ChannelLyaout = 0;                SampleRate = 0;                BitsPerSample = 0;                State = MediaState.None;                lastTime = TimeSpan.Zero;                MediaCompleted?.Invoke(Duration);            }        }        ///         /// 更改进度        ///         /// 更改到的位置(秒)        public void SeekProgress(int seekTime)        {            if (format == null || audioStreamIndex == null)                return;            lock (SyncLock)            {                IsPlaying = false;//将视频暂停播放                clock.Stop();                //将秒数转换成视频的时间戳                var timestamp = seekTime / ffmpeg.av_q2d(audioStream->time_base);                //将媒体容器里面的指定流(视频)的时间戳设置到指定的位置,并指定跳转的方法;                ffmpeg.av_seek_frame(format, audioStreamIndex, (long)timestamp, ffmpeg.AVSEEK_FLAG_BACKWARD | ffmpeg.AVSEEK_FLAG_FRAME);                ffmpeg.av_frame_unref(frame);//清除上一帧的数据                ffmpeg.av_packet_unref(packet); //清除上一帧的数据包                int error = 0;                //循环获取帧数据,判断获取的帧时间戳已经大于给定的时间戳则说明已经到达了指定的位置则退出循环                while (packet->pts < timestamp)                {                    do                    {                        do                        {                            ffmpeg.av_packet_unref(packet);//清除上一帧数据包                            error = ffmpeg.av_read_frame(format, packet);//读取数据                            if (error == ffmpeg.AVERROR_EOF)//是否是到达了视频的结束位置                                return;                        } while (packet->stream_index != audioStreamIndex);//判断当前获取的数据是否是视频数据                        ffmpeg.avcodec_send_packet(codecContext, packet);//将数据包发送给解码器解码                        error = ffmpeg.avcodec_receive_frame(codecContext, frame);//从解码器获取解码后的帧数据                    } while (error == ffmpeg.AVERROR(ffmpeg.EAGAIN));                }                OffsetClock = TimeSpan.FromSeconds(seekTime);//设置时间偏移                clock.Restart();//时钟从新开始                IsPlaying = true;//视频开始播放                lastTime = TimeSpan.Zero;            }        }        ///         /// 将音频帧转换成字节数组        ///         ///         ///         public byte[] FrameConvertBytes(AVFrame* sourceFrame)
  84.         {
  85.             var tempBufferPtr = bufferPtr;
  86.             //重采样音频
  87.             var outputSamplesPerChannel = ffmpeg.swr_convert(convert, &tempBufferPtr, frame->nb_samples, sourceFrame->extended_data, sourceFrame->nb_samples);
  88.             //获取重采样后的音频数据大小
  89.             var outPutBufferLength = ffmpeg.av_samples_get_buffer_size(null, 2, outputSamplesPerChannel, AVSampleFormat.AV_SAMPLE_FMT_S16, 1);
  90.             if (outputSamplesPerChannel < 0)
  91.                 return null;
  92.             byte[] bytes = new byte[outPutBufferLength];
  93.             //从内存中读取转换后的音频数据
  94.             Marshal.Copy(audioBuffer, bytes, 0, bytes.Length);
  95.             return bytes;
  96.         }        public void Play()        {            if (State == MediaState.Play)                return;            clock.Start();            IsPlaying = true;            State = MediaState.Play;        }        public void Pause()        {            if (State != MediaState.Play)                return;            IsPlaying = false;            OffsetClock = clock.Elapsed;            clock.Stop();            clock.Reset();            State = MediaState.Pause;        }        public void Stop()        {            if (State == MediaState.None)                return;            StopPlay();        }    }
复制代码
DecodecAudio 三.解码布局,和后台代码
  1. public unsafe class DecodecAudio : IMedia
  2.     {
  3.         //媒体格式容器
  4.         AVFormatContext* format;
  5.         //解码上下文
  6.         AVCodecContext* codecContext;
  7.         AVStream* audioStream;
  8.         //媒体数据包
  9.         AVPacket* packet;
  10.         AVFrame* frame;
  11.         SwrContext* convert;
  12.         int audioStreamIndex;
  13.         bool isNextFrame = true;
  14.         //播放上一帧的时间
  15.         TimeSpan lastTime;
  16.         TimeSpan OffsetClock;
  17.         object SyncLock = new object();
  18.         Stopwatch clock = new Stopwatch();
  19.         bool isNexFrame = true;
  20.         public event IMedia.MediaHandler MediaCompleted;
  21.         //是否是正在播放中
  22.         public bool IsPlaying { get; protected set; }
  23.         /// <summary>
  24.         /// 媒体状态
  25.         /// </summary>
  26.         public MediaState State { get; protected set; }
  27.         /// <summary>
  28.         /// 帧播放时长
  29.         /// </summary>
  30.         public TimeSpan frameDuration { get; protected set; }
  31.         /// <summary>
  32.         /// 媒体时长
  33.         /// </summary>
  34.         public TimeSpan Duration { get; protected set; }
  35.         /// <summary>
  36.         /// 播放位置
  37.         /// </summary>
  38.         public TimeSpan Position { get => OffsetClock + clock.Elapsed; }
  39.         /// <summary>
  40.         /// 解码器名字
  41.         /// </summary>
  42.         public string CodecName { get; protected set; }
  43.         /// <summary>
  44.         /// 解码器Id
  45.         /// </summary>
  46.         public string CodecId { get; protected set; }
  47.         /// <summary>
  48.         /// 比特率
  49.         /// </summary>
  50.         public long Bitrate { get; protected set; }
  51.         //通道数
  52.         public int Channels { get; protected set; }
  53.         //采样率
  54.         public long SampleRate { get; protected set; }
  55.         //采样次数
  56.         public long BitsPerSample { get; protected set; }
  57.         //通道布局
  58.         public ulong ChannelLyaout { get; protected set; }
  59.         /// <summary>
  60.         /// 采样格式
  61.         /// </summary>
  62.         public AVSampleFormat SampleFormat { get; protected set; }
  63.         public void InitDecodecAudio(string path)
  64.         {
  65.             int error = 0;
  66.             //创建一个 媒体格式上下文
  67.             format = ffmpeg.avformat_alloc_context();
  68.             var tempFormat = format;
  69.             //打开媒体文件
  70.             error = ffmpeg.avformat_open_input(&tempFormat, path, null, null);
  71.             if (error < 0)
  72.             {
  73.                 Debug.WriteLine("打开媒体文件失败");
  74.                 return;
  75.             }
  76.             //嗅探媒体信息
  77.             ffmpeg.avformat_find_stream_info(format, null);
  78.             AVCodec* codec;
  79.             //获取音频流索引
  80.             audioStreamIndex = ffmpeg.av_find_best_stream(format, AVMediaType.AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
  81.             if (audioStreamIndex < 0)
  82.             {
  83.                 Debug.WriteLine("没有找到音频流");
  84.                 return;
  85.             }
  86.             //获取音频流
  87.             audioStream = format->streams[audioStreamIndex];
  88.             //创建解码上下文
  89.             codecContext = ffmpeg.avcodec_alloc_context3(codec);
  90.             //将音频流里面的解码器参数设置到 解码器上下文中
  91.             error = ffmpeg.avcodec_parameters_to_context(codecContext, audioStream->codecpar);
  92.             if (error < 0)
  93.             {
  94.                 Debug.WriteLine("设置解码器参数失败");
  95.             }
  96.             error = ffmpeg.avcodec_open2(codecContext, codec, null);
  97.             //媒体时长
  98.             Duration = TimeSpan.FromMilliseconds(format->duration / 1000);
  99.             //编解码id
  100.             CodecId = codec->id.ToString();
  101.             //解码器名字
  102.             CodecName = ffmpeg.avcodec_get_name(codec->id);
  103.             //比特率
  104.             Bitrate = codecContext->bit_rate;
  105.             //音频通道数
  106.             Channels = codecContext->channels;
  107.             //通道布局类型
  108.             ChannelLyaout = codecContext->channel_layout;
  109.             //音频采样率
  110.             SampleRate = codecContext->sample_rate;
  111.             //音频采样格式
  112.             SampleFormat = codecContext->sample_fmt;
  113.             //采样次数  //获取给定音频参数所需的缓冲区大小。
  114.             BitsPerSample = ffmpeg.av_samples_get_buffer_size(null, 2, codecContext->frame_size, AVSampleFormat.AV_SAMPLE_FMT_S16, 1);
  115.             //创建一个指针
  116.             audioBuffer = Marshal.AllocHGlobal((int)BitsPerSample);
  117.             bufferPtr = (byte*)audioBuffer;
  118.             //初始化音频重采样转换器
  119.             InitConvert((int)ChannelLyaout, AVSampleFormat.AV_SAMPLE_FMT_S16, (int)SampleRate, (int)ChannelLyaout, SampleFormat, (int)SampleRate);
  120.             //创建一个包和帧指针
  121.             packet = ffmpeg.av_packet_alloc();
  122.             frame = ffmpeg.av_frame_alloc();
  123.             State = MediaState.Read;
  124.         }
  125.         //缓冲区指针
  126.         IntPtr audioBuffer;
  127.         //缓冲区句柄
  128.         byte* bufferPtr;
  129.         /// <summary>
  130.         /// 初始化重采样转换器
  131.         /// </summary>
  132.         /// <param name="occ">输出的通道类型</param>
  133.         /// <param name="osf">输出的采样格式</param>
  134.         /// <param name="osr">输出的采样率</param>
  135.         /// <param name="icc">输入的通道类型</param>
  136.         /// <param name="isf">输入的采样格式</param>
  137.         /// <param name="isr">输入的采样率</param>
  138.         /// <returns></returns>
  139.         bool InitConvert(int occ, AVSampleFormat osf, int osr, int icc, AVSampleFormat isf, int isr)
  140.         {
  141.             //创建一个重采样转换器
  142.             convert = ffmpeg.swr_alloc();
  143.             //设置重采样转换器参数
  144.             convert = ffmpeg.swr_alloc_set_opts(convert, occ, osf, osr, icc, isf, isr, 0, null);
  145.             if (convert == null)
  146.                 return false;
  147.             //初始化重采样转换器
  148.             ffmpeg.swr_init(convert);
  149.             return true;
  150.         }
  151.         /// <summary>
  152.         /// 尝试读取下一帧
  153.         /// </summary>
  154.         /// <param name="outFrame"></param>
  155.         /// <returns></returns>
  156.         public bool TryReadNextFrame(out AVFrame outFrame)
  157.         {
  158.             if (lastTime == TimeSpan.Zero)
  159.             {
  160.                 lastTime = Position;
  161.                 isNextFrame = true;
  162.             }
  163.             else
  164.             {
  165.                 if (Position - lastTime >= frameDuration)
  166.                 {
  167.                     lastTime = Position;
  168.                     isNextFrame = true;
  169.                 }
  170.                 else
  171.                 {
  172.                     outFrame = *frame;
  173.                     return false;
  174.                 }
  175.             }
  176.             if (isNextFrame)
  177.             {
  178.                 lock (SyncLock)
  179.                 {
  180.                     int result = -1;
  181.                     //清理上一帧的数据
  182.                     ffmpeg.av_frame_unref(frame);
  183.                     while (true)
  184.                     {
  185.                         //清理上一帧的数据包
  186.                         ffmpeg.av_packet_unref(packet);
  187.                         //读取下一帧,返回一个int 查看读取数据包的状态
  188.                         result = ffmpeg.av_read_frame(format, packet);
  189.                         //读取了最后一帧了,没有数据了,退出读取帧
  190.                         if (result == ffmpeg.AVERROR_EOF || result < 0)
  191.                         {
  192.                             outFrame = *frame;
  193.                             StopPlay();
  194.                             return false;
  195.                         }
  196.                         //判断读取的帧数据是否是视频数据,不是则继续读取
  197.                         if (packet->stream_index != audioStreamIndex)
  198.                             continue;
  199.                         //将包数据发送给解码器解码
  200.                         ffmpeg.avcodec_send_packet(codecContext, packet);
  201.                         //从解码器中接收解码后的帧
  202.                         result = ffmpeg.avcodec_receive_frame(codecContext, frame);
  203.                         if (result < 0)
  204.                             continue;
  205.                         //计算当前帧播放的时长
  206.                         frameDuration = TimeSpan.FromTicks((long)Math.Round(TimeSpan.TicksPerMillisecond * 1000d * frame->nb_samples / frame->sample_rate, 0));
  207.                         outFrame = *frame;
  208.                         return true;
  209.                     }
  210.                 }
  211.             }
  212.             else
  213.             {
  214.                 outFrame = *frame;
  215.                 return false;
  216.             }
  217.         }
  218.         void StopPlay()
  219.         {
  220.             lock (SyncLock)
  221.             {
  222.                 if (State == MediaState.None) return;
  223.                 IsPlaying = false;
  224.                 OffsetClock = TimeSpan.FromSeconds(0);
  225.                 clock.Reset();
  226.                 clock.Stop();
  227.                 var tempFormat = format;
  228.                 ffmpeg.avformat_free_context(tempFormat);
  229.                 format = null;
  230.                 var tempCodecContext = codecContext;
  231.                 ffmpeg.avcodec_free_context(&tempCodecContext);
  232.                 var tempPacket = packet;
  233.                 ffmpeg.av_packet_free(&tempPacket);
  234.                 var tempFrame = frame;
  235.                 ffmpeg.av_frame_free(&tempFrame);
  236.                 var tempConvert = convert;
  237.                 ffmpeg.swr_free(&tempConvert);
  238.                 Marshal.FreeHGlobal(audioBuffer);
  239.                 bufferPtr = null;
  240.                 audioStream = null;
  241.                 audioStreamIndex = -1;
  242.                 //视频时长
  243.                 Duration = TimeSpan.FromMilliseconds(0);
  244.                 //编解码器名字
  245.                 CodecName = String.Empty;
  246.                 CodecId = String.Empty;
  247.                 //比特率
  248.                 Bitrate = 0;
  249.                 //帧率
  250.               
  251.                 Channels = 0;
  252.                 ChannelLyaout = 0;
  253.                 SampleRate = 0;
  254.                 BitsPerSample = 0;
  255.                 State = MediaState.None;
  256.                 lastTime = TimeSpan.Zero;
  257.                 MediaCompleted?.Invoke(Duration);
  258.             }
  259.         }
  260.         /// <summary>
  261.         /// 更改进度
  262.         /// </summary>
  263.         /// <param name="seekTime">更改到的位置(秒)</param>
  264.         public void SeekProgress(int seekTime)
  265.         {
  266.             if (format == null || audioStreamIndex == null)
  267.                 return;
  268.             lock (SyncLock)
  269.             {
  270.                 IsPlaying = false;//将视频暂停播放
  271.                 clock.Stop();
  272.                 //将秒数转换成视频的时间戳
  273.                 var timestamp = seekTime / ffmpeg.av_q2d(audioStream->time_base);
  274.                 //将媒体容器里面的指定流(视频)的时间戳设置到指定的位置,并指定跳转的方法;
  275.                 ffmpeg.av_seek_frame(format, audioStreamIndex, (long)timestamp, ffmpeg.AVSEEK_FLAG_BACKWARD | ffmpeg.AVSEEK_FLAG_FRAME);
  276.                 ffmpeg.av_frame_unref(frame);//清除上一帧的数据
  277.                 ffmpeg.av_packet_unref(packet); //清除上一帧的数据包
  278.                 int error = 0;
  279.                 //循环获取帧数据,判断获取的帧时间戳已经大于给定的时间戳则说明已经到达了指定的位置则退出循环
  280.                 while (packet->pts < timestamp)
  281.                 {
  282.                     do
  283.                     {
  284.                         do
  285.                         {
  286.                             ffmpeg.av_packet_unref(packet);//清除上一帧数据包
  287.                             error = ffmpeg.av_read_frame(format, packet);//读取数据
  288.                             if (error == ffmpeg.AVERROR_EOF)//是否是到达了视频的结束位置
  289.                                 return;
  290.                         } while (packet->stream_index != audioStreamIndex);//判断当前获取的数据是否是视频数据
  291.                         ffmpeg.avcodec_send_packet(codecContext, packet);//将数据包发送给解码器解码
  292.                         error = ffmpeg.avcodec_receive_frame(codecContext, frame);//从解码器获取解码后的帧数据
  293.                     } while (error == ffmpeg.AVERROR(ffmpeg.EAGAIN));
  294.                 }
  295.                 OffsetClock = TimeSpan.FromSeconds(seekTime);//设置时间偏移
  296.                 clock.Restart();//时钟从新开始
  297.                 IsPlaying = true;//视频开始播放
  298.                 lastTime = TimeSpan.Zero;
  299.             }
  300.         }
  301.         /// <summary>
  302.         /// 将音频帧转换成字节数组
  303.         /// </summary>
  304.         /// <param name="sourceFrame"></param>
  305.         /// <returns></returns>
  306.         public byte[] FrameConvertBytes(AVFrame* sourceFrame)
  307.         {
  308.             var tempBufferPtr = bufferPtr;
  309.             //重采样音频
  310.             var outputSamplesPerChannel = ffmpeg.swr_convert(convert, &tempBufferPtr, frame->nb_samples, sourceFrame->extended_data, sourceFrame->nb_samples);
  311.             //获取重采样后的音频数据大小
  312.             var outPutBufferLength = ffmpeg.av_samples_get_buffer_size(null, 2, outputSamplesPerChannel, AVSampleFormat.AV_SAMPLE_FMT_S16, 1);
  313.             if (outputSamplesPerChannel < 0)
  314.                 return null;
  315.             byte[] bytes = new byte[outPutBufferLength];
  316.             //从内存中读取转换后的音频数据
  317.             Marshal.Copy(audioBuffer, bytes, 0, bytes.Length);
  318.             return bytes;
  319.         }
  320.         public void Play()
  321.         {
  322.             if (State == MediaState.Play)
  323.                 return;
  324.             clock.Start();
  325.             IsPlaying = true;
  326.             State = MediaState.Play;
  327.         }
  328.         public void Pause()
  329.         {
  330.             if (State != MediaState.Play)
  331.                 return;
  332.             IsPlaying = false;
  333.             OffsetClock = clock.Elapsed;
  334.             clock.Stop();
  335.             clock.Reset();
  336.             State = MediaState.Pause;
  337.         }
  338.         public void Stop()
  339.         {
  340.             if (State == MediaState.None)
  341.                 return;
  342.             StopPlay();
  343.         }
  344.     }
复制代码
Xaml
  1.   Task PlayTask;        CanvasBitmap bitmap;        DispatcherTimer timer = new DispatcherTimer();        bool progressActivity = false;        DecodecAudio audio = new DecodecAudio();        //NAudio音频播放组件
  2.         private WaveOut waveOut;
  3.         private BufferedWaveProvider bufferedWaveProvider;        public FFmpegDecodecAudio()        {            this.InitializeComponent();            Init();            InitUi();        }        void Init()        {            waveOut = new WaveOut();            bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat());            waveOut.Init(bufferedWaveProvider);            waveOut.Play();            //播放            play.Click += (s, e) =>            {                if (audio.State == MediaState.None)                {                    //初始化解码视频                    audio.InitDecodecAudio(pathBox.Text);                    DisplayVideoInfo();                }                audio.Play();                timer.Start();            };            //暂停            pause.Click += (s, e) => audio.Pause();            stop.Click += (s, e) => audio.Stop(); ;            PlayTask = new Task(() =>            {                while (true)                {                    //播放中                    if (audio.IsPlaying)                    {                        //获取下一帧视频                        if (audio.TryReadNextFrame(out var frame))                        {                            var bytes = audio.FrameConvertBytes(&frame);                            if (bytes == null)                                continue;                            if (bufferedWaveProvider.BufferLength             {                DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>                {                    timer.Stop();                    progressActivity = false;                    DisplayVideoInfo();                });            };        }        void InitUi()        {            //画布绘制            canvas.Draw += (s, e) =>            {                if (bitmap != null)                {                    var te = Win2DUlit.CalcutateImageCenteredTransform(canvas.ActualSize, bitmap.Size);                    te.Source = bitmap;                    e.DrawingSession.DrawImage(te);                }            };            timer.Interval = TimeSpan.FromMilliseconds(300);            //计时器更新进度条            timer.Tick += (s, e) =>            {                if (!audio.IsPlaying)                    return;                position.Text = audio.Position.ToString();                progressActivity = false;                progress.Value = audio.Position.TotalSeconds;                progressActivity = true;            };            //进度条更改            progress.ValueChanged += (s, e) =>            {                if (!audio.IsPlaying)                    return;                if (progressActivity == true)                {                    audio.SeekProgress((int)e.NewValue);                }            };        }        ///         /// 显示视频信息        ///         void DisplayVideoInfo()        {            dura.Text = audio.Duration.ToString();            audioCodec.Text = audio.CodecName;            audioBitrate.Text = audio.Bitrate.ToString();            audioChannels.Text = audio.Channels.ToString();            audioChannelsLayout .Text = audio.ChannelLyaout.ToString();            audioSampleRate.Text = audio.SampleRate.ToString();            audioBitsPerSample.Text = audio.BitsPerSample.ToString();            position.Text = audio.Position.ToString();            progress.Maximum = audio.Duration.TotalSeconds;        }
复制代码
View Code四.结语
  在整个解码和播放音频的过程中跟视频解码播放大致上是一样的,只有是重采样和读取数据的方式不一样而已,通过上面的代码就可以简单的实现音频播放,暂停,停止和更改进度的功能了
感兴趣的朋友可以到项目demo上了解运行情况。
项目Demo地址:LearnFFmppeg: 学习和记录ffmpeg - Gitee.com

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

莱莱

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表