Media Player: come svilupparne uno in C#

Per cominciare bisogna creare la nostra finestra grafica:

  1. Bisogna importare l’oggetto MediaElement all’interno della nostra finestra: le dimensioni sono a vostra discrezione e piacere poiché la finestra ha solitamente una misura standard iniziale di 500×300
  2. Il passo successivo è creare dei comandi che permettano all’utente di stoppare e riprodurre il file, nonché metterlo in pausa.
    Noi abbiamo deciso di sfruttare l’oggetto ToolBar che un tipo di oggetto che permette l’inserimento di pulsanti, immagini e altri tipi di oggetti che arricchiscono la GUI.
  3. Successivamente andremo ad aggiungere la barra di stato dove ci saranno i controlli del volume e uno Slider per poter mandare avanti e indietro il video.
  4. Infine bisogna aggiungere i vari eventi per permettere all’applicazione di funzionare:XAML della MainWindow:
    <Window x:Class="WpfApp2.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:WpfApp2"
     mc:Ignorable="d"
     Title="Media Player" Height="350" Width="525">
     <Window.CommandBindings>
     <CommandBinding Command="ApplicationCommands.Open" CanExecute="Open_CanExecute" Executed="Open_Executed" />
     <CommandBinding Command="MediaCommands.Play" CanExecute="Play_CanExecute" Executed="Play_Executed" />
     <CommandBinding Command="MediaCommands.Pause" CanExecute="Pause_CanExecute" Executed="Pause_Executed" />
     <CommandBinding Command="MediaCommands.Stop" CanExecute="Stop_CanExecute" Executed="Stop_Executed" />
     </Window.CommandBindings>
     <Grid MouseWheel="Grid_MouseWheel">
     <Grid.RowDefinitions>
     <RowDefinition Height="Auto" />
     <RowDefinition Height="*" />
     <RowDefinition Height="Auto" />
     </Grid.RowDefinitions>
     <ToolBar>
     <Button Command="ApplicationCommands.Open">
     <Image Source="images/1493679837_icon-folder.png" Height="26" />
     </Button>
     <Separator />
     <Button Command="MediaCommands.Play">
     <Image Source="images/1493679955_23_Play.png" Height="26" />
     </Button>
     <Button Command="MediaCommands.Pause">
     <Image Source="images/1493679959_25_Pause.png" Height="26" />
     </Button>
     <Button Command="MediaCommands.Stop">
     <Image Source="images/1493679953_24_Stop.png" Height="26" />
     </Button>
     </ToolBar>
    
    <MediaElement Name="mePlayer" Grid.Row="1" LoadedBehavior="Manual" Stretch="Uniform" />
    
    <StatusBar Grid.Row="2">
     <StatusBar.ItemsPanel>
     <ItemsPanelTemplate>
     <Grid>
     <Grid.ColumnDefinitions>
     <ColumnDefinition Width="Auto" />
     <ColumnDefinition Width="*" />
     <ColumnDefinition Width="Auto" />
     </Grid.ColumnDefinitions>
     </Grid>
     </ItemsPanelTemplate>
     </StatusBar.ItemsPanel>
     <StatusBarItem>
     <TextBlock Name="lblProgressStatus">00:00:00</TextBlock>
     </StatusBarItem>
     <StatusBarItem Grid.Column="1" HorizontalContentAlignment="Stretch">
     <Slider Name="sliProgress" Thumb.DragStarted="sliProgress_DragStarted" Thumb.DragCompleted="sliProgress_DragCompleted" ValueChanged="sliProgress_ValueChanged" />
     </StatusBarItem>
     <StatusBarItem Grid.Column="2">
     <ProgressBar Name="pbVolume" Width="50" Height="12" Maximum="1" Value="{Binding ElementName=mePlayer, Path=Volume}" />
     </StatusBarItem>
     </StatusBar>
     </Grid>
    </Window>

    CodeBehind Microsoft Visual C#:

    using Microsoft.Win32;
    using System;
    using System.Windows;
    using System.Windows.Controls.Primitives;
    using System.Windows.Input;
    using System.Windows.Threading;
    
    namespace WpfApp2
    {
     /// <summary>
     /// Logica di interazione per MainWindow.xaml
     /// </summary>
     public partial class MainWindow : Window
     {
     private string titolo = "Media Player";
     private bool mediaPlayerIsPlaying = false;
     private bool userIsDraggingSlider = false;
     public MainWindow()
     {
     InitializeComponent();
    
    DispatcherTimer timer = new DispatcherTimer();
     timer.Interval = TimeSpan.FromSeconds(1);
     timer.Tick += timer_Tick;
     timer.Start();
     }
    
    private void timer_Tick(object sender, EventArgs e)
     {
     if ((mePlayer.Source != null) && (mePlayer.NaturalDuration.HasTimeSpan) && (!userIsDraggingSlider))
     {
     sliProgress.Minimum = 0;
     sliProgress.Maximum = mePlayer.NaturalDuration.TimeSpan.TotalSeconds;
     sliProgress.Value = mePlayer.Position.TotalSeconds;
     }
     }
    
    private void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
     {
     e.CanExecute = true;
     }
    
    private void Open_Executed(object sender, ExecutedRoutedEventArgs e)
     {
     
     OpenFileDialog openFileDialog = new OpenFileDialog();
     openFileDialog.Filter = "File audio (*.mp3;*.mpg;*.mpeg)|*.mp3;*.mpg;*.mpeg|File video (*.mp4;*.avi;*.mov)|*.mp4;*.avi;*.mov|All files (*.*)|*.*";
     if (openFileDialog.ShowDialog() == true)
     {
     mePlayer.Source = new Uri(openFileDialog.FileName);
     Title = titolo + " - " + openFileDialog.SafeFileName;
     }
     }
    
    private void Play_CanExecute(object sender, CanExecuteRoutedEventArgs e)
     {
     e.CanExecute = (mePlayer != null) && (mePlayer.Source != null);
     }
    
    private void Play_Executed(object sender, ExecutedRoutedEventArgs e)
     {
     mePlayer.Play();
     mediaPlayerIsPlaying = true;
     }
    
    private void Pause_CanExecute(object sender, CanExecuteRoutedEventArgs e)
     {
     e.CanExecute = mediaPlayerIsPlaying;
     }
    
    private void Pause_Executed(object sender, ExecutedRoutedEventArgs e)
     {
     mePlayer.Pause();
     }
    
    private void Stop_CanExecute(object sender, CanExecuteRoutedEventArgs e)
     {
     e.CanExecute = mediaPlayerIsPlaying;
     }
    
    private void Stop_Executed(object sender, ExecutedRoutedEventArgs e)
     {
     mePlayer.Stop();
     mediaPlayerIsPlaying = false;
     }
    
    private void sliProgress_DragStarted(object sender, DragStartedEventArgs e)
     {
     userIsDraggingSlider = true;
     }
    
    private void sliProgress_DragCompleted(object sender, DragCompletedEventArgs e)
     {
     userIsDraggingSlider = false;
     mePlayer.Position = TimeSpan.FromSeconds(sliProgress.Value);
     }
    
    private void sliProgress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
     {
     lblProgressStatus.Text = TimeSpan.FromSeconds(sliProgress.Value).ToString(@"hh\:mm\:ss");
     }
    
    private void Grid_MouseWheel(object sender, MouseWheelEventArgs e)
     {
     mePlayer.Volume += (e.Delta > 0) ? 0.1 : -0.1;
     }
     }
    }

 

Eseguibile disponibile per il download:

 

Ti piacerebbe programmare con un Framework e dei linguaggi orientati agli oggetti? Segui questi tutorial ma non possiedi Visual Studio? NESSUN PROBLEMA!! Informatica e Software viene incontro a queste esigenze segnalandoti il sito ufficiale di Microsoft per scaricare Visual Studio Community:

Lascia un commento

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.