1. 程式人生 > >【C#】WPF音樂控制元件

【C#】WPF音樂控制元件

一、使用SoundPlayer

SoundPlayer 只能支援WAV格式的檔案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Media;//必須引用
using System.Windows.Media;//必須引用
using System.IO;
using System.Resources;//必須引用
//關鍵程式碼
SoundPlayer sp = new SoundPlayer
("音樂檔案路徑");//soundPlayer只能播放wav格式的音訊 sp.PlayLooping();//迴圈播放 sp.Play();//播放單次 sp.Stop();//停止 sp = new SoundPlayer(Properties.Resources.音樂檔名);//直接使用資原始檔內的音樂檔案

二、使用system.Windows.MediaPlayer

MediaPlayer支援的檔案型別很多,視訊音訊都能播放

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Media;//必須引用 using System.Windows.Media;//必須引用 using System.IO; using System.Resources;//必須引用 namespace MediaPlayer { //關鍵性程式碼 public class MusicPlayer { //例項化播放器,必須在類體內的最上面例項化,類體內全域性使用,否則會被垃圾回收機制很快回收,導致播放聲音很快就停止了。 MediaPlayer player = new MediaPlayer
(); player.Open(new Uri(@"../../Resources/音樂檔名.wav", UriKind.RelativeOrAbsolute));//mediaPlayer播放音樂 //UriKind.RelativeOrAbsolute Relative是相對路徑 Absolute是絕對路徑 URI是播放的路徑:"../../Resources/音樂檔名.wav" //路徑專用格式 player.Play();//播放音樂 player.Stop();//停止播放音樂

三、新增檔案到資原始檔夾,這樣實現系統自帶檔案。

在這裡插入圖片描述

四、選擇本地檔案功能


private void btnSelectMusic_Click(object sender, RoutedEventArgs e)
        {
			//初始化一個OpenFileDialog類
            OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Multiselect = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)////判斷使用者是否正確的選擇了檔案
            {
                GlobalData.musicLocal = openFileDialog1.FileNames;//傳給全域性變數
			//宣告允許的字尾名
				string[] str = new string[] { ".gif", ".jpge", ".jpg" };
                string file_path = openFileDialog1.FileName;//記錄選擇的檔案全路徑
			//如果我們要為彈出的選擇框中過濾檔案型別,可以設定OpenFileDialog的Filter屬性。比如我們只允許使用者選擇.xls檔案,可以作如下設定:

			fileDialog.Filter = "(*.xls)|*.xls";
            }
        }