一、在VLC中开启推送UDP流
再打开一个VLC测试一下:
注意:测试可以正常接收到UDP流之后要把上面这步打开的VLC关闭或停止播放,否则在下面的代码中无法播放(原因暂时没搞清楚,被坑了好久)
XAML
<Window x:Class="Test.Vlc.Udp.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:Test.Vlc.Udp" mc:Ignorable="d" xmlns:vlc="clr-namespace:LibVLCSharp.WPF;assembly=LibVLCSharp.WPF" Title="MainWindow" Height="450" Width="800"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <vlc:VideoView Background="LightBlue" x:Name="VideoViewer"/> <WrapPanel Grid.Row="1" HorizontalAlignment="Center"> <Button Height="30" Width="100" x:Name="Play" Content="播放" Click="Play_Click"/> <Button Height="30" Width="100" x:Name="Stop" Content="停止" Click="Stop_Click" Margin="30,0"/> </WrapPanel> </Grid> </Window>
CS
using LibVLCSharp.Shared; using System; using System.Threading.Tasks; using System.Windows; namespace Test.Vlc.Udp { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private async void Play_Click(object sender, RoutedEventArgs e) { await Task.Run(() => { Core.Initialize(); var _libvlc = new LibVLC(); _libvlc.Log += _libvlc_Log; Application.Current.Dispatcher.Invoke(() => VideoViewer.MediaPlayer = new LibVLCSharp.Shared.MediaPlayer(_libvlc)); var _media = new Media(_libvlc, "udp://@127.0.0.1:1234", FromType.FromLocation); //var _media = new Media(_libvlc, "udp://@localhost:1234", FromType.FromLocation); //_media.AddOption(":access=udp"); //_media.AddOption(":demux=mp4v"); //var _media = new Media(_libvlc, "rtsp://localhost:8554/111", FromType.FromLocation); //_media.AddOption(":access=rtsp-tcp"); _media.AddOption(":clock-synchro=0"); _media.AddOption(":live-caching=0"); _media.AddOption(":network-caching=1000"); _media.AddOption(":file-caching=0"); _media.AddOption(":grayscale"); Application.Current.Dispatcher.Invoke(() => VideoViewer.MediaPlayer.Play(_media)); }); } private void _libvlc_Log(object sender, LogEventArgs e) { Console.WriteLine(e.FormattedLog); } private void Stop_Click(object sender, RoutedEventArgs e) { VideoViewer.MediaPlayer?.Stop(); VideoViewer.MediaPlayer?.Dispose(); } } }