WPF下播放Rtmp的解决方案

介绍

在实际的开发过程中,需要在应用内部内嵌播放器进行视频的播放。官方默认的MediaElement控件只能播放有限的视频格式,也不能播放网络流。比较流行的解决方式是vlc的库,但是在实际使用过程中发现有很多问题。这里给大家推荐另一个比较好的库。

使用

官网地址

安装库

Nuget下安装FFME.Windows

bash 复制代码
PM> Install-Package FFME.Windows

下载ffmpeg依赖

注:官网给的地址我在实际使用中发现,使用官方的代码没问题,使用给定的步骤使用就会抱错,如果你们跟我一样给大家推荐另一个ffmpeg包的地址
ffmpeg依赖下载地址

代码

  1. 指定ffmpeg库的地址
csharp 复制代码
Unosquare.FFME.Library.FFmpegDirectory = @"C:\ffmpeg\ffmpeg-4.4-windows-desktop-vs2022-gpl-lite\bin";
  1. xaml中插入控件
csharp 复制代码
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1" 
        xmlns:ffme="clr-namespace:Unosquare.FFME;assembly=ffme.win"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Closed="Window_Closed"
        Title="MainWindow" Height="300" Width="600">
    <Grid>
        <ffme:MediaElement x:Name="Media" Background="Gray" LoadedBehavior="Play" UnloadedBehavior="Manual" />
        <Button Content="Play" Click="PlayButton_Click" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="10"/>
        <Button Content="Stop" Click="StopButton_Click" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="100,10,0,0"/>
    </Grid>
</Window>
  1. 监听失败的事件
csharp 复制代码
Media.MediaFailed += OnMediaFailed;
  1. 创建一个处理流地址的类FileInputStream
csharp 复制代码
namespace Unosquare.FFME.Windows.Sample.Foundation;

using Common;
using FFmpeg.AutoGen;
using System;
using System.IO;
using System.Runtime.InteropServices;

/// <inheritdoc />
/// <summary>
/// Provides an example of a very simple custom input stream.
/// </summary>
/// <seealso cref="IMediaInputStream" />
public sealed unsafe class FileInputStream : IMediaInputStream
{
    private readonly FileStream BackingStream;
    private readonly object ReadLock = new();
    private readonly byte[] ReadBuffer;

    /// <summary>
    /// Initializes a new instance of the <see cref="FileInputStream"/> class.
    /// </summary>
    /// <param name="path">The path.</param>
    public FileInputStream(string path)
    {
        var fullPath = Path.GetFullPath(path);
        BackingStream = File.OpenRead(fullPath);
        var uri = new Uri(fullPath);
        StreamUri = new Uri(uri.ToString().ReplaceOrdinal("file://", Scheme));
        CanSeek = true;
        ReadBuffer = new byte[ReadBufferLength];
    }

    /// <summary>
    /// The custom file scheme (URL prefix) including the :// sequence.
    /// </summary>
    public static string Scheme => "customfile://";

    /// <inheritdoc />
    public Uri StreamUri { get; }

    /// <inheritdoc />
    public bool CanSeek { get; }

    /// <inheritdoc />
    public int ReadBufferLength => 1024 * 16;

    /// <inheritdoc />
    public InputStreamInitializing OnInitializing { get; }

    /// <inheritdoc />
    public InputStreamInitialized OnInitialized { get; }

    /// <inheritdoc />
    public void Dispose()
    {
        BackingStream?.Dispose();
    }

    /// <summary>
    /// Reads from the underlying stream and writes up to <paramref name="targetBufferLength" /> bytes
    /// to the <paramref name="targetBuffer" />. Returns the number of bytes that were written.
    /// </summary>
    /// <param name="opaque">The opaque.</param>
    /// <param name="targetBuffer">The target buffer.</param>
    /// <param name="targetBufferLength">Length of the target buffer.</param>
    /// <returns>
    /// The number of bytes that have been read.
    /// </returns>
    public int Read(void* opaque, byte* targetBuffer, int targetBufferLength)
    {
        lock (ReadLock)
        {
            try
            {
                var readCount = BackingStream.Read(ReadBuffer, 0, ReadBuffer.Length);
                if (readCount > 0)
                    Marshal.Copy(ReadBuffer, 0, (IntPtr)targetBuffer, readCount);
                else if (readCount == 0)
                    return ffmpeg.AVERROR_EOF;

                return readCount;
            }
            catch (Exception)
            {
                return ffmpeg.AVERROR_EOF;
            }
        }
    }

    /// <inheritdoc />
    public long Seek(void* opaque, long offset, int whence)
    {
        lock (ReadLock)
        {
            try
            {
                return whence == ffmpeg.AVSEEK_SIZE ?
                    BackingStream.Length : BackingStream.Seek(offset, SeekOrigin.Begin);
            }
            catch
            {
                return ffmpeg.AVERROR_EOF;
            }
        }
    }
}
  1. 播放视频
csharp 复制代码
//var target = new Uri(@"rtmp://127.0.0.1/live/test1231233");
var target = new Uri(@"D:\视频\泥坑.mp4");
if (target.ToString().StartsWith(FileInputStream.Scheme, StringComparison.OrdinalIgnoreCase))
    await Media.Open(new FileInputStream(target.LocalPath));
else
    await Media.Open(target);
相关推荐
三千道应用题2 小时前
WPF&C#超市管理系统(6)订单详情、顾客注册、商品销售排行查询和库存提示、LiveChat报表
开发语言·c#·wpf
✎ ﹏梦醒͜ღ҉繁华落℘20 小时前
开发WPF项目时遇到的问题总结
wpf
hqwest2 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars2 天前
WPF中使用InputBindings进行快捷键绑定
wpf
hqwest2 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
hqwest2 天前
C#WPF实战出真汁01--项目介绍
开发语言·c#·wpf
wuty0073 天前
WPF 实现支持动态调整高度的文本显示控件
wpf·scrollviewer·extentheight·自动高度控件·动态调整高度
范纹杉想快点毕业6 天前
C 语言主控开发与显控开发能力体系及技术栈详解,STM32、QT、嵌入式、边缘系统显示
stm32·单片机·tcp/ip·microsoft·fpga开发·51单片机·wpf
weixin_447103586 天前
WPF之绑定!
c#·wpf
DataIntel6 天前
wpf问题记录
wpf