First of all I would like to welcome everyone to my new blog and wish you all a happy new year… Through this blog I hope I can provide help, tips and some useful information about common problems we’ve all faced in programming, as well as some sample applications... In my first post I’m going to show you how you can easily create your own custom Media Player which can automatically search for lyrics for the song you’re listening.

To begin, we are going to create a new WPF application (in this demo I am going to use the .NET 4 Framework and Visual Studio 2010, but most of the functions mentioned in this post are also available on .NET 3.5).

The next thing we are going to do is to add 4 buttons and a mediaElement to our MainWindow by dragging them from the toolbox we have available here. These 4 buttons cover the main 4 functions of a media player, play, pause, stop, open. I am not going to give you any instructions on how to “reshape” them as I believe the best GUI is the one you make yourself, so this is up to you.

Let’s open the MainWindow.xaml.cs file now and create the play, pause and stop functions.

.bool fileIsPlaying;
.//play the file
.private void playButton__Click(object sender, RoutedEventArgs e)
.{
. mediaElement.Play();
. fileIsPlaying = true;
.}
.
.
.//pause the file
.private void pauseButton_Click(object sender, RoutedEventArgs e)
.{
. mediaElement.Pause();
. fileIsPlaying = false;
.}
.
.
.//stop the file
.private void stopButton_Click(object sender, RoutedEventArgs e)
.{
. mediaElement.Stop();
. fileIsPlaying = false;
.}

The code behind the open button is a little bit more complex

.private void openFileButton_Click(object sender, RoutedEventArgs e)
. {
. Stream checkStream = null;
. OpenFileDialog dlg = new OpenFileDialog();
. dlg.Filter = "All Supported File Types(*.mp3,*.wav,*.mpeg,*.wmv,*.avi)|*.mp3;*.wav;*.mpeg;*.wmv;*.avi";
. // Show open file dialog box
. if ((bool)dlg.ShowDialog())
. {
. try
. {
. // check if something is selected
. if ((checkStream = dlg.OpenFile()) != null)
. {
. mediaElement.Source = new Uri(dlg.FileName);
. }
. }
. catch (Exception ex)
. {
. MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
. }
. }
. }

You can easily change the file types allowed by users in the OpenFileDialog just by changing this value.

            dlg.Filter = "All Supported File Types (*.mp3,*.wav,*.mpeg,*.wmv,*.avi)|*.mp3;*.wav;*.mpeg;*.wmv;*.avi";

You can also create 2 sliders in order to control the volume and the speed ratio of the playback. You should add these properties into your XAML file :

  • for the speedRatioSlider

    Value="" Maximum="" SmallChange="0.25"
  • for the volumeSlider
    Value="0.5" Maximum="" SmallChange="0.01" LargeChange="0.1"

    So now we’re finally able to edit our c# code and create the events.

    .//change the speed of the playback
    .void speedRatioSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double /> e)
    .{
    . mediaElement.SpeedRatio = speedRatioSlider.Value;
    .
    .}
    .
    .//turn volume up-down
    .private void volumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double /> e)
    .{
    . mediaElement.Volume = volumeSlider.Value;
    .}

    Now there’s one more thing we need to do. We have to create a slide bar attached to this mediaElement to show the progress made. For this task we’re going to need a slider, a progress bar and a Timer to periodically change the values of these elements. First of all we need to create a DispatcherTimer and an event that will occur every 1 second, in order to change the value of the textbox displaying the current progress of the playback.

    .DispatcherTimer timer;
    .
    .public delegate void timerTick();
    .timerTick tick;
    .
    .public MainWindow()
    . {
    . InitializeComponent();
    .
    . timer = new DispatcherTimer();
    . timer.Interval = TimeSpan.FromSeconds();
    . timer.Tick += new EventHandler(timer_Tick);
    . tick = new timerTick(changeStatus);
    .
    . }
    .
    .
    .void timer_Tick(object sender, EventArgs e)
    . {
    . Dispatcher.Invoke(tick);
    . }

    We’ll use the Position property of the mediaElement (which is, though, available only after the mediaElement_MediaOpened event occurs) to change the value of the textbox that displays the current time of the playback.

    .//visualize progressBar
    .//the fileIsPlaying variable is true when the media is playing
    .//and false when the media is paused or stopped
    . void changeStatus()
    . {
    . if (fileIsPlaying)
    . {
    . string sec, min, hours;
    .
    . #region customizeTime
    . if (mediaElement.Position.Seconds < )
    . sec = "" + mediaElement.Position.Seconds.ToString();
    . else
    . sec = mediaElement.Position.Seconds.ToString();
    .
    .
    . if (mediaElement.Position.Minutes < )
    . min = "" + mediaElement.Position.Minutes.ToString();
    . else
    . min = mediaElement.Position.Minutes.ToString();
    .
    . if (mediaElement.Position.Hours < )
    . hours = "" + 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 == )
    . {
    .
    . currentTimeTextBlock.Text = min + ":" + sec;
    . }
    . else
    . {
    . currentTimeTextBlock.Text = hours + ":" + min + ":" + sec;
    . }
    . }
    . }

    So now we have the current time displayed on the textbox and the progress of the playback. We have to create the events for the following functions of the seekSlider

    .//seek to desirable position of the file
    .//you will also have to set the moveToPosition property of the seekSlider to
    .//true
    .private void seekSlider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    . {
    . TimeSpan ts = new TimeSpan(, , , , (int)seekSlider.Value);
    .
    . changePostion(ts);
    . }
    .
    .//mouse down on slide bar in order to seek
    . private void seekSlider_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    . {
    . isDragging = true;
    . }
    .
    .private void seekSlider_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    . {
    . if (isDragging)
    . {
    . TimeSpan ts = new TimeSpan(, , , , (int)seekSlider.Value);
    . changePostion(ts);
    . }
    . isDragging = false;
    . }
    .
    .//change position of the file
    .void changePostion(TimeSpan ts)
    .{
    . mediaElement.Position = ts;
    .}

    Finally we need to implement the mediaElement_MediaOpened and mediaElement_MediaEnded functions.

    .
    .
    .
    . //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()
    . {
    . ......
    . }
    .
    .
    .
    .//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);
    . }

    That’s all for now…We have created our own, fully functional media Player.. You can download the sample code here...I would be happy to read any thoughts or suggestions you might have…

  • 原文链接

Custom Media Player in WPF (Part 1)的更多相关文章

  1. 用VLC Media Player搭建简单的流媒体服务器

    VLC可以作为播放器使用,也可以搭建服务器. 在经历了Helix Server和Darwin Streaming Server+Perl的失败之后,终于找到了一个搭建流媒体简单好用的方法. 这个网址中 ...

  2. android错误之MediaPlayer用法的Media Player called in state *,androidmediaplayer

    用到Media Player,遇到几个问题,记一下 用法就不说了,使用的时候最好参考一下mediaPlayer的这张图 第一个错误是Media Player called in state 8 这个是 ...

  3. win7自带windows media player 已停止工作

    解决方法如下: 在计算机开始,菜单找到控制面板 ,然后打开程序和功能,选择打开或关闭window功能,媒体功能.再取消windows Media Center Windows MediaPlayer选 ...

  4. 转:Media Player Classic - HC 源代码分析

    VC2010 编译 Media Player Classic - Home Cinema (mpc-hc) Media Player Classic - Home Cinema (mpc-hc)播放器 ...

  5. Media Player 把光盘中的内容拷贝出来的方法

    http://jingyan.baidu.com/article/cb5d610529f0c1005c2fe0b4.html  这个链接是通过Media  Player 把光盘中的内容拷贝出来的方法h ...

  6. 20 Free Open Source Web Media Player Apps

    free Media Players (Free MP3, Video, and Music Player ...) are cool because they let web developers ...

  7. Windows Media Player安装了却不能播放网页上的视频

    前段时间遇到Windows Media Player安装了却不能播放网页上的视频的问题,在网上查找资料时,发现大部分资料都没能解决我这个问题.偶尔试了网上一牛人的方法,后来竟然解决了.现在再找那个网页 ...

  8. 如何在Windows中打开多个Windows Media Player

    博客搬到了fresky.github.io - Dawei XU,请各位看官挪步.最新的一篇是:如何在Windows中打开多个Windows Media Player.

  9. Windows Media Player axWindowsMediaPlayer1 分类: C# 2014-07-28 12:04 195人阅读 评论(0) 收藏

    属性/方法名: 说明: [基本属性] URL:String; 指定媒体位置,本机或网络地址 uiMode:String; 播放器界面模式,可为Full, Mini, None, Invisible p ...

随机推荐

  1. Spring MVC集成Tiles使用方法

    首先,我们定义一个总体的tiles视图 /tiles/mainTemplate.jsp首先使用:<tiles:getAsString name="title"/>打印t ...

  2. 页面提交错误,页面间参数传递java.lang.NumberFormatException: null

    多次出现这样的错误,在点击一个按钮触发提交整个页面的事件时,总是报错,不止一次出现这样的错误了. 出现这种问题的分析: 1 我们从这个问题的本身来看,java.lang.NumberFormatExc ...

  3. redis 获取key 过期时间

    <pre name="code" class="html">127.0.0.1:6379> keys *b4f107c6-e96c-4a1e- ...

  4. 14.2.5.2 Clustered and Secondary Indexes

    14.2.5.2 Clustered and Secondary Indexes : 每个InnoDB 表 有一个特别的索引称为clustered index 行数据存储的地方. 典型的,cluste ...

  5. xvfb 初步探究

    有时候我们不关注程序是否有界面(比如自动化测试),只要程序在运行就可以了 很感谢 xvfb 这个工具给我们提供了相关的功能 比如在没有 X server 的机器上运行 gedit, 可以用下面的命令 ...

  6. 枚举类型互相转换(使用GetEnumName和TypeInfo两个函数)

    usesClasses,TypInfo ; typeTCommandType = (ctEmptyCommand,ctAdd,ctModify); TCommandTypeConvert=classp ...

  7. New 和 GetMem 的不同之处

    如果操作一个 record 指针中的字符串变量,会不会丢失 string 的内 存空间,造成内存泄漏? 结果是:使用 New() 分配的内存,会自动初始化 record 的内容,并且在 Dispose ...

  8. 【夯实基础】Spring在ssh中的作用

    尊重版权:http://blog.csdn.net/qjlsharp/archive/2009/03/21/4013255.aspx 写的真不错. 在SSH框假中spring充当了管理容器的角色.我们 ...

  9. 不断摸索发现用 andy 模拟器很不错,感觉跟真机差不多

    嗯,今天也遇到了模拟的问题.那个慢啊,好几分钟才能开机,加载程序总共差不多十几分钟.当时想如果真做android开发必须换电脑啊.后来不断摸索发现用 andy 模拟器很不错,感觉跟真机差不多. 还是真 ...

  10. (读书笔记).NET大局观-.NET语言(1)

    通用语言运行时 通用语言运行时被明确设计为支持多种语言,一般而言,建立于CLR之上的语言可以获得共同的良好处理.通过一个宏大的核心语义集,CLR还界定了一个以它为基础的典型编程语言的大体部分.例如对于 ...