怎么在c#中使用winform制作一个音乐播放器
作者
这篇文章将为大家详细讲解有关怎么在c#中使用winform制作一个音乐播放器,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
AxWindowsMediaPlayer的方法
1 首先新建一个页面 如图所示: 图片左侧是列表 使用listview 右侧是背景图片。图片框框的地方是后面可以实现的,+和-按钮分别代表添加文件和删除文件 还有就是控制播放的顺序。下面的分别是修改歌词的字体 和展示/隐藏
2 新建一个透明的歌词页面[窗体]
3 新建一个半透明的页面[窗体]
4 业务代码
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; usingWMPLib; usingSystem.Media; usingSystem.IO; usingSystem.Text.RegularExpressions; usingAxWMPLib; usingSystem.Drawing.Drawing2D; usingCCWin; namespaceKenMusicPlayer { publicpartialclassMusicPlayer:Skin_DevExpress { publicintindex=1; publicintlistIndex; privateboolfirst_in=true;//是否第一次进入歌词区域 privateboolshowLrc=true;//默认显示歌词 privateintimageInd=0;//播放的图片下标 privateListimageList;//播放的图片 privatePointclosePoint;//关闭按钮的位置 privateSizedfSize;//最初的位置 //声音 SoundPlayerplayer=newSoundPlayer(); Dictionary dic=newDictionary (); //播放列表 Dictionary playListDict=newDictionary (); List al=newList ();//当前歌词时间表 IWMPMediamedia; /* *下面这一大段API调用,主要是用来设置歌词窗口的滚动条的 *但其实后面,我并没有怎么用到,只是在将滚动条滚动到底部时,用了一下 */ privateconstintWM_VSCROLL=0x115; privateconstintSB_HORZ=0; privateconstintSB_VERT=1; privateconstintSB_CTL=2; privateconstintSB_BOTH=3; privateconstintSB_LINEUP=0; privateconstintSB_LINELEFT=0; privateconstintSB_LINEDOWN=1; privateconstintSB_LINERIGHT=1; privateconstintSB_PAGEUP=2; privateconstintSB_PAGELEFT=2; privateconstintSB_PAGEDOWN=3; privateconstintSB_PAGERIGHT=3; privateconstintSB_THUMBPOSITION=4; privateconstintSB_THUMBTRACK=5; privateconstintSB_TOP=6; privateconstintSB_LEFT=6; privateconstintSB_BOTTOM=7; privateconstintSB_RIGHT=7; privateconstintSB_ENDSCROLL=8; privateconstintWM_PAINT=0x000F; [System.Runtime.InteropServices.DllImport("user32.dll")] publicstaticexternboolScrollWindow(IntPtrhWnd,intXAmount,intYAmount,refRectanglelpRect,refRectanglelpClipRect); [System.Runtime.InteropServices.DllImport("user32.dll")] publicstaticexternintSetScrollPos(IntPtrhwnd,intnBar,intnPos,boolbRedraw); [System.Runtime.InteropServices.DllImport("user32.dll")] publicstaticexternintSetScrollPos(intnBar,intnPos,boolbRedraw); [System.Runtime.InteropServices.DllImport("user32.dll")] publicstaticexternintGetScrollPos(IntPtrhwnd,intnBar); [System.Runtime.InteropServices.DllImport("user32.dll")] publicstaticexternboolUpdateWindow(IntPtrhWnd); [System.Runtime.InteropServices.DllImport("user32.dll")] publicstaticexternintSendMessage(IntPtrhwnd,intwMsg,intwParam,intlParam); publicvoidsetWord() { } publicMusicPlayer() { this.StartPosition=FormStartPosition.CenterScreen;//窗口居中显示 InitializeComponent(); } privatevoidMusicPlayer_Load(objectsender,EventArgse) { InitLoad(); } /// ///初始化加载播放列表如歌词背景图定时器等等 /// privatevoidInitLoad() { try { boolflag=false; stringfolder=Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"bgImages"); DirectoryInforoot=newDirectoryInfo(folder); FileInfo[]files=root.GetFiles(); stringfileName; for(inti=0;i(); this.pictureBox1.Image=Image.FromFile(files[i].FullName); } imageList.Add(files[i].FullName); flag=true; } } playerType.Text=playerType.Items[0].ToString();//默认第一个 closePoint=this.skinButtonClose.Location; dfSize=this.Size; richTextBox1.BackColor=this.TransparencyKey; skinComboBoxFontName.Text=skinComboBoxFontName.Items[0].ToString();//默认第一个 skinComboBoxFontSize.Text=skinComboBoxFontSize.Items[0].ToString();//默认第一个 ComboBoxSkinSelect.Text=ComboBoxSkinSelect.Items[0].ToString();//默认第一个 //this.BackPalace=Image.FromFile(ComboBoxSkinSelect.Items[0].ToString());//默认第一个 lvDetail.AllowDrop=true; lvDetail.View=View.Details; lvDetail.DragEnter+=Files_DragEnter;//对象拖拽事件 lvDetail.DragDrop+=Files_DragDrop;//拖拽操作完成事件 //wmp.OpenStateChange+=WMP_OpenStateChange; wmp.PlayStateChange+=WMP_PlayStateChange; timerImgs.Start(); } catch(Exceptionex) { Console.WriteLine("错误:"+ex.Message); } } /// ///提供给透明歌词窗口的定时器调用的 /// ///publicvoidshowTmform(bools) { if(s) { this.btmForm.Show(); if(this.first_in) { this.lrcForm.TopMost=true; Pointpoint=this.Location; point.Y=point.Y+this.Height; this.lrcForm.Location=point; this.btmForm.Location=point; this.lrcForm.Width=this.Width; this.btmForm.Width=this.Width; this.first_in=false; } } else { this.first_in=true; this.btmForm.Hide(); } } /// ///播放时会进入这个事件 /// ////// privatevoidWMP_PlayStateChange(objectsender,_WMPOCXEvents_PlayStateChangeEvente) { loadLrc(); } /// ///拖拽操作完成事件 /// ////// privatevoidFiles_DragDrop(objectsender,DragEventArgse) { try { stringfileName,fileExtension,fileSize,temp; FileInfofi=null; ListViewItemlvi=null; Arrayarray=(Array)e.Data.GetData(DataFormats.FileDrop); Regexregex=newRegex("(\\.mp3|\\.wav|\\.wma)"); stringfilePath; for(inti=0;i ///插入播放列表和字典集 /// /// /// /// /// /// /// /// privatevoidInsertPlayList(outstringfileName,outstringfileExtension,outstringfileSize,outstringtemp,outFileInfofileInfo,outListViewItemlistViewItem,stringfilePath) { fileInfo=newFileInfo(filePath); temp=filePath.Remove(filePath.LastIndexOf('.')); fileName=Path.GetFileNameWithoutExtension(filePath); fileExtension=Path.GetExtension(filePath); fileSize=(fileInfo.Length/1024).ToString()+"KB"; listViewItem=newListViewItem(); listViewItem.Text=index++.ToString(); listViewItem.SubItems.AddRange(newstring[]{fileName,fileExtension,fileSize,filePath}); lvDetail.Items.Add(listViewItem); //添加到播放列表 media=wmp.newMedia(filePath); //listIndex++, //wmp.currentPlaylist.insertItem(media); wmp.currentPlaylist.appendItem(media); playListDict.Add(filePath,media); //杜绝重复项 dic.Add(filePath,fileName); } /// ///文件拖拽进入 /// ////// privatevoidFiles_DragEnter(objectsender,DragEventArgse) { if(e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect=DragDropEffects.Link; } else { e.Effect=DragDropEffects.None; } } /// ///导入文件 /// privatevoidtsmiLoading_Click(objectsender,EventArgse) { stringfileName,fileExtension,fileSize,temp; FileInfofi=null; ListViewItemlvi=null; openFileDialog1.Multiselect=true; openFileDialog1.Filter="mp3文件(*.mp3)|*.mp3|wav文件(*.wav)|*.wav|wma文件(*.wma)|*.wma"; if(openFileDialog1.ShowDialog()==DialogResult.OK) { //顺序播放 wmp.settings.setMode("shuffle",false); foreach(stringfilePathinopenFileDialog1.FileNames) { if(!dic.ContainsKey(filePath)) { InsertPlayList(outfileName,outfileExtension,outfileSize,outtemp,outfi,outlvi,filePath); } } } } //////清除列表 /// privatevoidListViewClear_Click(objectsender,EventArgse) { lvDetail.Items.Clear(); } //////播放 /// privatevoidtsmiPlayer_Click(objectsender,EventArgse) { wmp.Ctlcontrols.play(); } //////暂停 /// privatevoidtsmiWaiting_Click(objectsender,EventArgse) { wmp.Ctlcontrols.pause(); } //////停止 /// privatevoidtsmiStop_Click(objectsender,EventArgse) { wmp.Ctlcontrols.stop(); } //////退出 /// privatevoidtsmiExit_Click(objectsender,EventArgse) { Application.Exit(); } //////双击某项播放 /// privatevoidlvDetail_DoubleClick(objectsender,EventArgse) { if(lvDetail.SelectedItems.Count>0) { wmp.currentMedia=wmp.currentPlaylist.Item[int.Parse(lvDetail.SelectedItems[0].Text)-1]; } } //////循环播放 /// ////// privatevoidtsmiXunHuan_Click(objectsender,EventArgse) { //点击项 ToolStripMenuItemcurrentItem=(ToolStripMenuItem)sender; ToolStripItemCollectionitems=this.tsmiSet.DropDownItems; ToolStripMenuItemitem; for(inti=0;i ///图片宽高设置 /// /// /// /// publicstaticImageResizeImage(ImageimgToResize,Sizesize) { //获取图片宽度 intsourceWidth=imgToResize.Width; //获取图片高度 intsourceHeight=imgToResize.Height; floatnPercent=0; floatnPercentW=0; floatnPercentH=0; //计算宽度的缩放比例 nPercentW=((float)size.Width/(float)sourceWidth); //计算高度的缩放比例 nPercentH=((float)size.Height/(float)sourceHeight); if(nPercentH ///定时器执行的方法,每隔1秒执行一次歌词逐行显示 /// /// /// privatevoidShowLineLrc(objectsender,EventArgse) { this.label1.Text=this.wmp.Ctlcontrols.currentPositionString; if(this.lrcForm==null) { this.lrcForm=newTMForm(); Pointpos=this.Location; pos.Y=lrcForm.Location.Y+lrcForm.Height; this.Location=pos; this.btmForm=newBTMForm(); MusicPlayermainForm=(MusicPlayer)this.Owner; btmForm.Location=pos; this.lrcForm.Owner=this; this.btmForm.Owner=this; this.btmForm.Hide(); this.lrcForm.Show(); } if(this.wmp.currentMedia==null) { this.richTextBox1.Text=""; return; } stringdurationString=this.wmp.currentMedia.durationString; inttrackBarValue=Convert.ToInt32(this.wmp.Ctlcontrols.currentPosition); //this.trackBar1.Maximum=Convert.ToInt32(this.wmp.currentMedia.duration); //this.trackBar1.Value=Convert.ToInt32(this.wmp.Ctlcontrols.currentPosition); if(this.richTextBox1.Text!="歌词文件不存在"&&this.richTextBox1.Text!="歌词文件内容为空") { intpos=al.IndexOf(trackBarValue.ToString()); boolisAr=this.richTextBox1.Text.Contains("歌手:"); boolisTi=this.richTextBox1.Text.Contains("歌名:"); if(pos>=0) { intn=isAr?1:0; intm=isTi?1:0; intheight=28*(this.al.Count+m+n); intmax=height-this.richTextBox1.Height; this.richTextBox1.SelectAll(); this.richTextBox1.SelectionColor=Color.Black; this.richTextBox1.SelectionLength=0;/**/ intl=this.richTextBox1.Lines[pos+m+n].Length; this.richTextBox1.Select(this.richTextBox1.GetFirstCharIndexFromLine(pos+m+n),l); this.richTextBox1.SelectionColor=Color.OrangeRed; this.richTextBox1.SelectionLength=0; //this.Text=GetScrollPos(this.richTextBox1.Handle,SB_VERT).ToString()+"-"+al.Count+"-"+this.richTextBox1.Height; if((pos+m+n)*28<=max) { intstart=this.richTextBox1.GetFirstCharIndexFromLine(pos+m+n); this.richTextBox1.SelectionStart=start; this.richTextBox1.ScrollToCaret(); } else { //this.richTextBox1.Focus(); SendMessage(this.richTextBox1.Handle,WM_VSCROLL,SB_BOTTOM,0); UpdateWindow(this.richTextBox1.Handle); //this.richTextBox1.SelectionStart=this.richTextBox1.Text.Length; //this.richTextBox1.ScrollToCaret(); } if(this.lrcForm!=null) { stringl1=this.richTextBox1.Lines[pos+m+n]; stringl2; if((pos+m+n) =(this.trackBar1.Maximum-2)) { this.PlayModeChange(); }*/ } /// ///载入歌词 /// ///歌词路径名 publicvoidloadLrc() { if(this.wmp.playState==WMPPlayState.wmppsPlaying) { IWMPMediacurrentMedia=wmp.currentMedia; stringfullPath=currentMedia.sourceURL; stringgeciPath=Path.Combine(Path.GetDirectoryName(fullPath),Path.GetFileNameWithoutExtension(fullPath)+".lrc"); //播放哪个资源列表需选中 ListView.ListViewItemCollectionlistViewItems=lvDetail.Items; lvDetail.FullRowSelect=true; for(inti=0;i ///删除选中的文件并停止播放 /// /// /// privatevoidskinButton2_Click(objectsender,EventArgse) { try { ListView.SelectedIndexCollectionindexes=this.lvDetail.SelectedIndices; if(indexes.Count>0) { intindex=indexes[0]; stringpath=this.lvDetail.Items[index].SubItems[4].Text; IWMPPlaylistiWMPPlaylist=wmp.currentPlaylist; //先移除播放列表再移除listview列表 wmp.currentPlaylist.removeItem(playListDict[path]); playListDict.Remove(path); this.lvDetail.Items[index].Remove(); dic.Remove(path); wmp.Ctlcontrols.stop(); } } catch(Exceptionex) { MessageBox.Show("操作失败!\n"+ex.Message,"提示",MessageBoxButtons.OK, MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button1); } } /// ///列表鼠标双击事件 /// ////// privatevoidlvDetail_MouseDoubleClick(objectsender,MouseEventArgse) { try { ListView.SelectedIndexCollectionindexes=this.lvDetail.SelectedIndices; if(indexes.Count>0) { intindex=indexes[0]; stringpath=this.lvDetail.Items[index].SubItems[4].Text; wmp.Ctlcontrols.playItem(playListDict[path]); //wmp.URL=path;//这种方式会失去播放列表【不是肉眼可见的listview列表】 wmp.Ctlcontrols.stop(); wmp.Ctlcontrols.play(); } } catch(Exceptionex) { MessageBox.Show("操作失败!\n"+ex.Message,"提示",MessageBoxButtons.OK, MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button1); } } /// ///字体改变 /// ////// privatevoidskinComboBoxFontName_SelectedIndexChanged(objectsender,EventArgse) { if(this.lrcForm!=null) { this.lrcForm.ChangeLabelFont(this.skinComboBoxFontName.SelectedItem.ToString(),this.skinComboBoxFontSize.SelectedItem.ToString()); } } /// ///字体大小改变 /// ////// privatevoidskinComboBox1_SelectedIndexChanged(objectsender,EventArgse) { if(this.lrcForm!=null) { this.lrcForm.ChangeLabelFont(this.skinComboBoxFontName.SelectedItem.ToString(),this.skinComboBoxFontSize.SelectedItem.ToString()); } } /// ///歌词是否显示 /// ////// privatevoidskinButton5_Click(objectsender,EventArgse) { if(this.lrcForm==null) { return; } this.showLrc=!this.showLrc; this.skinButton5.Text=this.showLrc?"关闭":"显示"; if(this.showLrc) { this.btmForm.Show(); this.lrcForm.Show(); } else { this.btmForm.Hide(); this.lrcForm.Hide(); } } /// ///背景图片切换 /// ////// privatevoidtimerImgs_Tick(objectsender,EventArgse) { if(imageInd<=imageList.Count-2) { imageInd++; this.pictureBox1.Image.Dispose(); this.pictureBox1.Image=Image.FromFile(imageList[imageInd]); } else { imageInd=0; } } /// ///粘贴音乐到播放列表 /// ////// privatevoidlvDetail_KeyDown(objectsender,KeyEventArgse) { System.Collections.Specialized.StringCollectionstringCollection=Clipboard.GetFileDropList(); if(stringCollection!=null) { stringfileName,fileExtension,fileSize,temp; FileInfofi=null; ListViewItemlvi=null; foreach(variteminstringCollection) { if((item.ToLower().EndsWith(".mp3")|| item.ToLower().EndsWith(".wav")|| item.ToLower().EndsWith(".wma"))&&!dic.ContainsKey(item)) { InsertPlayList(outfileName,outfileExtension,outfileSize,outtemp,outfi,outlvi,item); } } } } //选择皮肤 privatevoidComboBoxSkinSelect_SelectedIndexChanged(objectsender,EventArgse) { stringbgColor=ComboBoxSkinSelect.SelectedItem.ToString(); if(!string.IsNullOrEmpty(ComboBoxSkinSelect.SelectedItem.ToString())) { switch(bgColor) { case"渐变黑": this.BorderPalace=kenMusicPlayer.Properties.Resources.bg_black; break; case"天蓝色": this.BorderPalace=kenMusicPlayer.Properties.Resources.bg_light_blue; break; case"墨绿色": this.BorderPalace=kenMusicPlayer.Properties.Resources.bg_green; break; case"蓝色": this.BorderPalace=kenMusicPlayer.Properties.Resources.bg_s_blue; break; case"浅灰色": this.BorderPalace=kenMusicPlayer.Properties.Resources.bg_grey; break; case"亮色": this.BorderPalace=kenMusicPlayer.Properties.Resources.bg_light; break; default: this.BorderPalace=kenMusicPlayer.Properties.Resources.bg_black; break; } /*this.UpdateStyles(); this.Update();*/ //this.BackPalace=Image.FromFile(ComboBoxSkinSelect.SelectedItem.ToString()); } } /// ///退出 /// ////// privatevoidskinButtonClose_Click(objectsender,EventArgse) { //this.Close(); Application.Exit(); } privatevoidMusicPlayer_Resize(objectsender,EventArgse) { try { Sizesize=this.Size; intx=(size.Width-dfSize.Width)+closePoint.X; inty=closePoint.Y;//(size.Height-dfSize.Height)+closePoint.Y; Pointpoint=newPoint(x,y); this.skinButtonClose.Location=point; } catch(Exceptionex) { Console.WriteLine("异常:"+ex.Message); } } /// ///改方法也是提供给透明歌词窗口用的,用来修改半透明窗体的位置,是透明歌词窗口和半透明窗体始终重合 /// ///publicvoidmoveTmform(Pointpos) { this.btmForm.Location=pos; } } }
关于怎么在c#中使用winform制作一个音乐播放器就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
目录