WPF MediaElement播放器2

时间:2023-01-31 23:11:51

在此问个问题,MediaElement播放本地和http上的视频没问题,但是ftp的怎么在本例中播放不了

若高手了解,请不吝赐教

WPF MediaElement播放器2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using System.Windows.Threading;
using System.Threading;
using System.Data;
using System.Windows.Forms;

namespace MediaPlayer_Beta
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        DispatcherTimer timer;

        public delegate void timerTick();
        timerTick tick;

        bool isDragging = false;
        bool fileIsPlaying = false;
        string sec, min, hours;

        public MainWindow()
        {
            this.Left = 0;
            this.Top = 0;
            InitializeComponent();
            seekSlider.Width = SystemParameters.MaximizedPrimaryScreenWidth - 150;
            this.WindowState = System.Windows.WindowState.Maximized;
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timer_Tick);
            tick = new timerTick(changeStatus);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            Dispatcher.Invoke(tick);
        }


        //visualize progressBar 
        void changeStatus()
        {
            if (fileIsPlaying)
            {

                #region customizeTime
                if (mediaElement.Position.Seconds < 10)
                    sec = "0" + mediaElement.Position.Seconds.ToString();
                else
                    sec = mediaElement.Position.Seconds.ToString();


                if (mediaElement.Position.Minutes < 10)
                    min = "0" + mediaElement.Position.Minutes.ToString();
                else
                    min = mediaElement.Position.Minutes.ToString();

                if (mediaElement.Position.Hours < 10)
                    hours = "0" + mediaElement.Position.Hours.ToString();
                else
                    hours = mediaElement.Position.Hours.ToString();

                #endregion customizeTime

                seekSlider.Value = mediaElement.Position.TotalMilliseconds;
                progressBar.Value = mediaElement.Position.TotalMilliseconds;

                if (mediaElement.Position.Hours == 0)
                {

                    currentTimeTextBlock.Text = min + ":" + sec;
                }
                else
                {
                    currentTimeTextBlock.Text = hours + ":" + min + ":" + sec;
                }
            }
        }


        //open the file
        private void openFileButton_Click(object sender, RoutedEventArgs e)
        {
            string FileName = "http://mschannel9.vo.msecnd.net/o9/mix/09/wmv/key01.wmv";
            //"ftp://test:123456@192.168.1.75/media/Linux.wmv";//Ftp测试不能播放,需下载本地再打开
            //"e:\\text\\dian\\media\\test.avi";
            mediaElement.Source = new Uri(FileName);
            Thread.Sleep(50);
            mediaElement.Close();
            mediaElement.Play();
        }


        //occurs when the file is opened
        public void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            timer.Start();
            fileIsPlaying = true;
            openMedia();
        }


        //opens media,adds file to playlist and gets file info
        public void openMedia()
        {
            InitializePropertyValues();
            try
            {
                #region customizeTime
                if (mediaElement.NaturalDuration.TimeSpan.Seconds < 10)
                    sec = "0" + mediaElement.Position.Seconds.ToString();
                else
                    sec = mediaElement.NaturalDuration.TimeSpan.Seconds.ToString();

                if (mediaElement.NaturalDuration.TimeSpan.Minutes < 10)
                    min = "0" + mediaElement.NaturalDuration.TimeSpan.Minutes.ToString();
                else
                    min = mediaElement.NaturalDuration.TimeSpan.Minutes.ToString();

                if (mediaElement.NaturalDuration.TimeSpan.Hours < 10)
                    hours = "0" + mediaElement.NaturalDuration.TimeSpan.Hours.ToString();
                else
                    hours = mediaElement.NaturalDuration.TimeSpan.Hours.ToString();

                if (mediaElement.NaturalDuration.TimeSpan.Hours == 0)
                {

                    endTimeTextBlock.Text = min + ":" + sec;
                }
                else
                {
                    endTimeTextBlock.Text = hours + ":" + min + ":" + sec;
                }

                #endregion customizeTime
            }
            catch { }
            string path = mediaElement.Source.LocalPath.ToString();

            double duration = mediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
            seekSlider.Maximum = duration;
            progressBar.Maximum = duration;

            mediaElement.Volume = volumeSlider.Value;
            mediaElement.SpeedRatio = speedRatioSlider.Value + 1;
            mediaElement.ScrubbingEnabled = true;

            volumeSlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(volumeSlider_ValueChanged);
            speedRatioSlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(speedRatioSlider_ValueChanged);
        }

        //occurs when the file is done playing
        private void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            mediaElement.Stop();
            volumeSlider.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(volumeSlider_ValueChanged);
            speedRatioSlider.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(speedRatioSlider_ValueChanged);
        }


        //initialize properties of file
        void InitializePropertyValues()
        {
            mediaElement.Volume = (double)volumeSlider.Value;
            mediaElement.SpeedRatio = (double)speedRatioSlider.Value + 1;
        }


        //seek to desirable position of the file
        private void seekSlider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)seekSlider.Value);

            changePostion(ts);
        }


        //mouse down on slide bar in order to seek
        private void seekSlider_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            fileIsPlaying = false;
        }


        private void seekSlider_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (isDragging)
            {
                TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)seekSlider.Value);
                changePostion(ts);
                fileIsPlaying = true;
            }
            isDragging = false;
        }


        //change position of the file
        void changePostion(TimeSpan ts)
        {
            mediaElement.Position = ts;
        }


        //change the speed of the playback
        void speedRatioSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            mediaElement.SpeedRatio = speedRatioSlider.Value + 1;
            speedTextBlock.Text = speedRatioSlider.Value + "x";
        }

        //play the file
        private void playButton__Click(object sender, RoutedEventArgs e)
        {
            fileIsPlaying = true;
            mediaElement.Play();
            timer.Start();
        }


        //pause the file
        private void pauseButton_Click(object sender, RoutedEventArgs e)
        {
            fileIsPlaying = false;
            mediaElement.Pause();
            timer.Stop();
        }


        //stop the file
        private void stopButton_Click(object sender, RoutedEventArgs e)
        {
            fileIsPlaying = false;
            timer.Stop();
            mediaElement.Stop();
            seekSlider.Value = 0;
            progressBar.Value = 0;
            currentTimeTextBlock.Text = "00:00";
        }


        //turn volume up-down
        private void volumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            mediaElement.Volume = volumeSlider.Value;
        }

    }
}
<Window
        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"
        mc:Ignorable="d"
        x:Class="MediaPlayer_Beta.MainWindow"
        IsHitTestVisible="True" Background="#00000000" ResizeMode="CanResize" IsTabStop="True" 
        Grid.IsSharedSizeScope="True" UseLayoutRounding="True" HorizontalContentAlignment="Center" 
        WindowStyle="ThreeDBorderWindow" AllowsTransparency="False" d:DesignHeight="385" d:DesignWidth="585">
    <Grid  x:Name="mainGrid" Background="#FF0A0A0A" Height="{Binding}">
        <Grid.RowDefinitions>
            <RowDefinition Height="286*" />
            <RowDefinition Height="23" />
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>
        <MediaElement MediaEnded="mediaElement_MediaEnded" MediaOpened="mediaElement_MediaOpened" LoadedBehavior="Manual" HorizontalAlignment="Right" Name="mediaElement" VerticalAlignment="Bottom" Opacity="1" AllowDrop="True" Stretch="Fill" IsMuted="False" />
        <Button Content="打开" Height="30" HorizontalAlignment="Left" Margin="220,0,0,0" Name="openFileButton" VerticalAlignment="Top" Width="66" Click="openFileButton_Click" Background="#FF030303" Foreground="#FFE8E8E8" Grid.Row="2" />
        <Button x:Name="stopButton" Content="停止" Margin="149,0,0,0" Click="stopButton_Click" Background="#FF030303" Foreground="#FFE8E8E8" HorizontalAlignment="Left" Width="65" Grid.Row="2" />
        <Slider Height="30" HorizontalAlignment="Left" Margin="292,0,0,0" Name="volumeSlider" VerticalAlignment="Top" Width="87" Value="0.5" Maximum="1" SmallChange="0.01" LargeChange="0.1" Background="Black" Foreground="#FFDBDBDB" IsMoveToPointEnabled="True" Grid.Row="2"></Slider>
        <Slider Name="speedRatioSlider" VerticalAlignment="Center" Value="0" Width="70" Margin="385,0,0,0" Maximum="3" SmallChange="1" Background="Black" UseLayoutRounding="True" TickPlacement="BottomRight" Foreground="#FFDBDBDB" Height="30" Grid.Row="2" HorizontalAlignment="Left"></Slider>
        <Button x:Name="pauseButton" Content="暂停" Margin="71,0,0,0" Click="pauseButton_Click" Background="#FF030303" Foreground="#FFE8E8E8" Width="76" HorizontalAlignment="Left" Grid.Row="2" />
        <Button x:Name="playButton_" Content="播放" HorizontalAlignment="Left" Width="65" Click="playButton__Click" ClipToBounds="True" Background="#FF030303" Foreground="#FFE8E8E8" Grid.Row="2" Margin="4,0,0,0" />
        <TextBlock Height="23" Name="endTimeTextBlock" Text="00:00" Width="68" Background="{x:Null}" Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="495,0,0,0" FlowDirection="RightToLeft" Grid.Row="1" TextAlignment="Center"></TextBlock>
        <TextBlock Height="23" Name="currentTimeTextBlock" Text="00:00" Width="68" Background="Black" Foreground="#FFDBDBDB" TextAlignment="Center" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="4,0,0,0" Grid.Row="1"></TextBlock>
        <Slider Width="{Binding}" PreviewMouseLeftButtonUp="seekSlider_PreviewMouseLeftButtonUp" PreviewMouseLeftButtonDown="seekSlider_PreviewMouseLeftButtonDown" MouseLeftButtonUp="seekSlider_MouseLeftButtonUp" Name="seekSlider" Background="{x:Null}" Foreground="Red" BorderBrush="{x:Null}" IsMoveToPointEnabled="True" TickPlacement="None" SnapsToDevicePixels="False" OpacityMask="{x:Null}" IsManipulationEnabled="True" IsSnapToTickEnabled="False" IsSelectionRangeEnabled="False" IsTabStop="False" AutoToolTipPlacement="None" AllowDrop="False" Height="23" VerticalAlignment="Center" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" HorizontalAlignment="Center" Grid.Row="1"  Margin="68,0,68,0"></Slider>
        <ProgressBar Height="6" Name="progressBar" Background="#00000000" BorderBrush="Black" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="68,0,68,0" Grid.Row="1" IsHitTestVisible="False" BorderThickness="0" Foreground="#FF0089FF"></ProgressBar>
        <TextBlock Height="24" Name="speedTextBlock" Text="0x" Width="34" Background="{x:Null}" Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="460,7,0,0" FlowDirection="RightToLeft" Grid.Row="2" TextAlignment="Right"></TextBlock>
    </Grid>
</Window>