MediaElementを使って動画ファイルを再生します。
プロジェクトの作成
dotnet new wpf -n VideoPlayer
cd VideoPlayer
code .
ソースコード
ファイル名:MainWindow.xaml
<Window x:Class="VideoPlayer.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:VideoPlayer"
mc:Ignorable="d"
Title="MainWindow" Height="720" Width="1280">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0" HorizontalAlignment="Center">
<TextBox x:Name="MovieFileTextBox" Height="30" Margin="10" Width="1000"></TextBox>
<Button x:Name="FileSelectButton" Height="30" Margin="10" Width="100" Click="FileSelect">ファイル選択</Button>
</StackPanel>
<MediaElement
x:Name="MovieControl"
Grid.Row="1"
LoadedBehavior="Manual"
UnloadedBehavior="Stop">
</MediaElement>
<StackPanel Orientation="Horizontal" Grid.Row="2" HorizontalAlignment="Center">
<Button x:Name="PlayButton" Height="30" Width="100" Margin="10" Click="PlayClick">再生</Button>
<Button x:Name="PauseButton" Height="30" Width="100" Margin="10" Click="PauseClick">一時停止</Button>
<Button x:Name="StopButton" Height="30" Width="100" Margin="10" Click="StopClick">停止</Button>
</StackPanel>
</Grid>
</Window>
ファイル名:MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace VideoPlayer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void FileSelect(object sender, EventArgs e)
{
var d =new OpenFileDialog();
d.InitialDirectory = @"c:\";
d.ShowDialog();
MovieFileTextBox.Text = d.FileName;
MovieControl.Source = new Uri(MovieFileTextBox.Text);
}
public void PlayClick(object sender, EventArgs e)
{
if (MovieFileTextBox.Text == "") return;
MovieControl.Play();
}
public void PauseClick(object sender, EventArgs e)
{
MovieControl.Pause();
}
public void StopClick(object sender, EventArgs e)
{
MovieControl.Stop();
}
}
}
コメント