在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# 音乐播放器源码(可播放avi/mp3/wav等格式)

C# 音乐播放器源码(可播放avi/mp3/wav等格式)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:2.83M
  • 下载次数:56
  • 浏览次数:1000
  • 发布时间:2018-07-25
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.rar
  • 所需积分:2
 相关标签: Mp3 播放器 C# 音乐 播放

实例介绍

【实例简介】原理:使用 Windows Media Player,使用 IrisSkin 可换肤

【实例截图】

from clipboard


from clipboard


from clipboard


from clipboard


需要启用 Windows Media Player 功能,否则会提示【System.Runtime.InteropServices.COMException:“没有注册类】

操作步骤:控制面板>>程序>>启用或者关闭windows 功能>>选中 媒体功能>>Windows Media Player,点击确定即可

from clipboard


【核心代码】


using Sunisoft.IrisSkin;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MusicPlayer
{
    public partial class MainForm : Form
    {
        #region 属性和构造函数

        private BackgroundWorker bgWorker1;//自动切换图片线程

        private BackgroundWorker bgWorker2;//显示歌词

        private string[] bgUrls;//图片Url

        private int curIndex = 0;//当前图片索引

        private bool isRunning = false;

        private string[] curLyric;

        private SkinEngine skinEngine;

        public MainForm()
        {
            InitializeComponent();
        }

        #endregion

        private void MainForm_Load(object sender, EventArgs e)
        {
            InitInfo();
            this.lblLyric.Parent = this.pbImage;

            //初始化歌曲列表
            List<MediaInfo> lstMedias = new List<MediaInfo>() {
                 new MediaInfo()
                 {
                    Id = "001",
                    Name = "一起走过的日子",
                    XPath = @"E:\d\KuGou\刘德华 - 一起走过的日子.mp3",
                    Lyric = @"E:\d\KuGou\刘德华 - 一起走过的日子.lrc",
                    XIcon=global::MusicPlayer.Properties.Resources.music
                }
            };

            this.bsMediaList.DataSource = lstMedias;
            this.dgMediaList.AutoGenerateColumns = false;
            this.dgMediaList.DataSource = this.bsMediaList;
            //
            this.dgHistory.AutoGenerateColumns = false;
            
            //初始化背后事件
            this.bgWorker1 = new BackgroundWorker();
            this.bgWorker1.WorkerSupportsCancellation = true;
            this.bgWorker1.DoWork  = BgWorker1_DoWork;

            this.bgWorker2 = new BackgroundWorker();
            this.bgWorker2.WorkerSupportsCancellation = true;
            this.bgWorker2.DoWork  = BgWorker2_DoWork;
            
            //背景图列表
            this.bgUrls = new string[3] {
                "http://old.bz55.com/uploads/allimg/160322/139-1603221A304.jpg",
                "http://cimage.tianjimedia.com/uploadImages/thirdImages/2017/107/54XO1649NK8S.jpg",
                "http://pic1.win4000.com/wallpaper/f/549cf3e9be982.jpg"
            };
        }

        /// <summary>
        /// 初始化皮肤
        /// </summary>
        private void InitInfo()
        {
            this.skinEngine = new SkinEngine();
            this.skinEngine.SkinFile = AppDomain.CurrentDomain.BaseDirectory   @"Skins\mp10.ssk";
            this.skinEngine.DisableTag = 9999;
            ReadSkinFile();
        }

        /// <summary>
        /// 背景图切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (isRunning) {
                if (bgUrls != null && bgUrls.Length > 0) {
                    this.curIndex = (this.curIndex % bgUrls.Length);
                    this.pbImage.Image = Image.FromStream(HttpWebRequest.Create(bgUrls[this.curIndex]).GetResponse().GetResponseStream());
                    this.pbImage.SizeMode = PictureBoxSizeMode.StretchImage;
                    this.curIndex  ;
                    //
                    this.lblTime.Invoke(new Action(() =>
                    {
                        this.lblTime.Text = string.Format("{0}/{1}", this.axWindowsMediaPlayer1.Ctlcontrols.currentPositionString, this.axWindowsMediaPlayer1.currentMedia.durationString);
                        //this.lblTime.ForeColor = Color.White;
                    }));
                    
                }
                Thread.Sleep(2000);
            }
        }

        /// <summary>
        /// 歌词显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BgWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            while (isRunning && this.curLyric!=null) {
                showLyric();
                Thread.Sleep(500);
            }
        }

        /// <summary>
        /// 歌曲列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgMediaList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1) {
                this.axWindowsMediaPlayer1.Ctlcontrols.stop();
                MediaInfo mi = this.dgMediaList.Rows[e.RowIndex].DataBoundItem as MediaInfo;
                this.axWindowsMediaPlayer1.URL = mi.XPath;
                //歌词
                ReadLyricFromFile(mi.Lyric);
                this.axWindowsMediaPlayer1.Ctlcontrols.play();
                //
                if (!this.bgWorker1.IsBusy)
                {
                    this.isRunning = true;
                    this.bgWorker1.RunWorkerAsync();
                }
                this.lblLyric.Text = mi.Name;
                if (!this.bgWorker2.IsBusy && this.curLyric!=null) {
                    this.isRunning = true;
                    this.bgWorker2.RunWorkerAsync();
                }
                if (!this.bsMediaHistory.Contains(mi))
                {
                    this.bsMediaHistory.Add(mi);
                }
               
            }
        }


        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.isRunning = false;
        }

        /// <summary>
        /// 播放状态改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {

        }

        /// <summary>
        /// 显示歌词
        /// </summary>
        private void showLyric()
        {
            try
            {
                if (this.curLyric != null && this.curLyric.Length > 0)
                {
                    double cur = this.axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
                    double total = this.axWindowsMediaPlayer1.currentMedia.duration;
                    string curString = this.axWindowsMediaPlayer1.Ctlcontrols.currentPositionString;
                    int v = (int)Math.Ceiling((cur / total) * curLyric.Length);
                    string vi = string.Empty;
                    if (v < 15)
                    {
                        if (v < 5)
                        {
                            vi = string.Join("\n", this.curLyric, 0, 5);
                        }
                        else
                        {
                            //如果小于15条,则逐条显示
                            vi = string.Join("\n", this.curLyric, 0, v   5);
                        }
                    }
                    else {
                        //否则,只显示15条,感觉向上滚动。
                        vi = string.Join("\n", this.curLyric, v - 10, 15);
                    }
                    this.lblLyric.Invoke(new Action(() =>
                    {
                        this.lblLyric.Text = vi;
                    }));

                }
            }
            catch (Exception ex) {

            }
        }

        /// <summary>
        /// 从文件中读取歌词
        /// </summary>
        /// <param name="file"></param>
        public void ReadLyricFromFile(string file) {
            if (File.Exists(file))
            {
                using (FileStream fs = new FileStream(file, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                    {
                        string temp = sr.ReadToEnd();
                        string[] tempArr = temp.Split('\n');
                        this.curLyric = new string[tempArr.Length - 4];
                        for (int i = 4; i < tempArr.Length; i  )
                        {
                            int index = tempArr[i].IndexOf("]");
                            this.curLyric[i - 4] = index == -1 ? tempArr[i] : tempArr[i].Substring(tempArr[i].IndexOf("]")   1);
                        }
                    }
                }
            }
            else {
                this.curLyric = null;
            }
        }

        private void btnMediaList_Click(object sender, EventArgs e)
        {
            this.dgMediaList.Visible = !this.dgMediaList.Visible;
        }

        private void btnHistory_Click(object sender, EventArgs e)
        {
            this.dgHistory.Visible = !this.dgHistory.Visible;
        }

        /// <summary>
        /// 读取皮肤文件
        /// </summary>
        private void ReadSkinFile() {
            string folder = AppDomain.CurrentDomain.BaseDirectory   "Skins";
            string[] files = Directory.GetFiles(folder);
            foreach (string file in files)
            {
                this.tdBtnSkins.DropDownItems.Add(Path.GetFileNameWithoutExtension(file), null, new EventHandler(tdBtnSkins_ItemClick));
            }

        }

        /// <summary>
        /// 换肤事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tdBtnSkins_ItemClick(object sender, EventArgs e) {
            string folder = AppDomain.CurrentDomain.BaseDirectory   "Skins";
            string name = sender.ToString();
            string skinFile = string.Format(@"{0}\{1}.ssk", folder, name);
            this.skinEngine.SkinFile = skinFile;
        }

        /// <summary>
        /// 添加本地歌曲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.AddExtension = false;
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.Tag = "请将歌词和音乐文件放在相同目录";
            ofd.Filter = "Audio文件(*.avi)|*.avi|WAV文件(*.wav)|*.wav |MP3文件(*.mp3)|*.mp3|所有文件(*.*)|*.* ";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                MediaInfo mi = new MediaInfo()
                {
                    Id = "002",
                    Name = Path.GetFileNameWithoutExtension(ofd.FileName),
                    XPath = ofd.FileName,
                    Lyric =Path.GetDirectoryName(ofd.FileName) "\\"  Path.GetFileNameWithoutExtension(ofd.FileName)   ".lrc",
                    XIcon = global::MusicPlayer.Properties.Resources.music
                };
                this.bsMediaList.Add(mi);
            }
        }

        /// <summary>
        /// 历史记录事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgHistory_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                this.axWindowsMediaPlayer1.Ctlcontrols.stop();
                MediaInfo mi = this.dgHistory.Rows[e.RowIndex].DataBoundItem as MediaInfo;
                this.axWindowsMediaPlayer1.URL = mi.XPath;
                //歌词
                ReadLyricFromFile(mi.Lyric);
                this.axWindowsMediaPlayer1.Ctlcontrols.play();
                //
                if (!this.bgWorker1.IsBusy)
                {
                    this.isRunning = true;
                    this.bgWorker1.RunWorkerAsync();
                }
                this.lblLyric.Text = mi.Name;
                if (!this.bgWorker2.IsBusy && this.curLyric != null)
                {
                    this.isRunning = true;
                    this.bgWorker2.RunWorkerAsync();
                }
                if (!this.bsMediaHistory.Contains(mi))
                {
                    this.bsMediaHistory.Add(mi);
                }

            }
        }
    }
}


实例下载地址

C# 音乐播放器源码(可播放avi/mp3/wav等格式)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警