C#控制檯應用實現音樂播放器初步(一)


首先介紹一下這個功能還沒有完善的項目

clsMCI.cs文件如下:

using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MusicDemo
{
    public class clsMCI
    {
        public clsMCI()
        {
        }
        //定義API函數使用的字符串變量 
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        private string Name = "";
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
        private string durLength = "";
        [MarshalAs(UnmanagedType.LPTStr, SizeConst = 128)]
        private string TemStr = "";
        int ilong;
        //定義播放狀態枚舉變量
        public enum State
        {
            mPlaying = 1,
            mPuase = 2,
            mStop = 3
        };
        //結構變量
        public struct structMCI
        {
            public bool bMut;
            public int iDur;
            public int iPos;
            public int iVol;
            public int iBal;
            public string iName;
            public State state;
        };
        public structMCI mc = new structMCI();
        //取得播放文件屬性
        public string FileName
        {
            get
            {
                return mc.iName;
            }
            set
            {
                try
                {
                    TemStr = "";
                    TemStr = TemStr.PadLeft(127, Convert.ToChar(" "));
                    Name = Name.PadLeft(260, Convert.ToChar(" "));
                    mc.iName = value;
                    ilong = APIClass.GetShortPathName(mc.iName, Name, Name.Length);
                    Name = GetCurrPath(Name);
                    Name = "open " + Convert.ToChar(34) + Name + Convert.ToChar(34) + " alias media";
                    ilong = APIClass.mciSendString("close all", TemStr, TemStr.Length, 0);
                    ilong = APIClass.mciSendString(Name, TemStr, TemStr.Length, 0);
                    ilong = APIClass.mciSendString("set media time format milliseconds", TemStr, TemStr.Length, 0);
                    mc.state = State.mStop;
                }
                catch
                {
                }
            }
        }
        //播放
        public void play()
        {
            TemStr = "";
            TemStr = TemStr.PadLeft(127, Convert.ToChar(" "));
            APIClass.mciSendString("play media", TemStr, TemStr.Length, 0);
            mc.state = State.mPlaying;
        }
        //停止
        public void StopT()
        {
            TemStr = "";
            TemStr = TemStr.PadLeft(128, Convert.ToChar(" "));
            ilong = APIClass.mciSendString("close media", TemStr, 128, 0);
            ilong = APIClass.mciSendString("close all", TemStr, 128, 0);
            mc.state = State.mStop;
        }
        public void Puase()
        {
            TemStr = "";
            TemStr = TemStr.PadLeft(128, Convert.ToChar(" "));
            ilong = APIClass.mciSendString("pause media", TemStr, TemStr.Length, 0);
            mc.state = State.mPuase;
        }
        private string GetCurrPath(string name)
        {
            if (name.Length < 1) return "";
            name = name.Trim();
            name = name.Substring(0, name.Length - 1);
            return name;
        }
        //總時間
        public int Duration
        {
            get
            {
                durLength = "";
                durLength = durLength.PadLeft(128, Convert.ToChar(" "));
                APIClass.mciSendString("status media length", durLength, durLength.Length, 0);
                durLength = durLength.Trim();
                if (durLength == "") return 0;
                return (int)(Convert.ToDouble(durLength) / 1000f);
            }
        }
        //當前時間
        public int CurrentPosition
        {
            get
            {
                durLength = "";
                durLength = durLength.PadLeft(128, Convert.ToChar(" "));
                APIClass.mciSendString("status media position", durLength, durLength.Length, 0);
                mc.iPos = (int)(Convert.ToDouble(durLength) / 1000f);
                return mc.iPos;
            }
        }
    }
    public class APIClass
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern int GetShortPathName(
         string lpszLongPath,
         string shortFile,
         int cchBuffer
      );
        [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
        public static extern int mciSendString(
           string lpstrCommand,
           string lpstrReturnString,
           int uReturnLength,
           int hwndCallback
          );
    }
}

Menu.cs文件如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MusicDemo
{
    class Menu
    {
        public Menu()
        {
            this.Ano = "上下箭頭選擇 Enter鍵確認";
            this.CurrentItem = -1;
        }
        public Menu(string title)
        {
            this.Title = title;
            this.Ano = "上下箭頭選擇 Enter鍵確認";
            this.CurrentItem = -1;
        }
        public string Title
        {
            get;
            set;
        }

        public string Ano
        {
            set;
            get;
        }

        public int CurrentItem
        {
            get;
            set;
        }

        List<MenuItem> items = new List<MenuItem>();

        //新增菜單項
        public bool addItem(MenuItem newItem)
        {
            foreach (MenuItem item in items)
            {
                if (item.Id == newItem.Id)
                    return false;
            }
            if (this.items.Count == 0)
                this.CurrentItem = 0;
            this.items.Add(newItem);
            return true;
        }

        //打印
        public int Show()
        {
            Console.Clear();
            Console.ResetColor();
            Console.WriteLine(Title);

            for(int i =0; i<items.Count;i ++){

                if(CurrentItem ==i)
                    Console.BackgroundColor = ConsoleColor.Blue;
                else
                    Console.BackgroundColor = ConsoleColor.Black;
                Console.WriteLine("{0}、{1}", items[i].Id, items[i].Name);
            }

            Console.ResetColor();
            Console.WriteLine(this.Ano);

            Console.CursorVisible = false;
            return Action(Console.ReadKey(true).Key);
        }
        //處理鍵盤動作
        public int Action(ConsoleKey inputKey)
        {
            if (inputKey == ConsoleKey.UpArrow)
            {
                if (this.CurrentItem > 0)
                    this.CurrentItem--;
                this.Show();
                return -1;
            }
            else if (inputKey == ConsoleKey.DownArrow)
            {
                if (this.CurrentItem < this.items.Count - 1)
                    this.CurrentItem++;
                this.Show();
                return -1;
            }
            else if (inputKey == ConsoleKey.Enter)
            {
                items[this.CurrentItem].Select();
                return items[this.CurrentItem].Id;
            }

            this.Show();
            return -1;
        }
        //刪除所有項
        public void Clear()
        {
            this.items.Clear();
        }
    }
}

MenuItem.cs文件內容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace MusicDemo
{
    delegate void ItemSelect(MenuItem item);

    class MenuItem
    {
        public MenuItem(int id, string name)
        {
            this.Id = id;
            this.Name = name;
        }
        public MenuItem(int id, string name,ItemSelect select)
        {
            this.Id = id;
            this.Name = name;
            this.SelectEvent += select;
        }

        public event ItemSelect SelectEvent;

        public int Id
        {
            set;
            get;
        }
        public string Name
        {
            get;
            set;
        }

        public void Select(){
            if (null != SelectEvent)
                SelectEvent(this);
        }
    }
}

MusiceMain.cs文件內容如下:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Forms;

namespace MusicDemo
{
    class MusiceMain
    {
        static Menu mainMenu = null;
        static Menu musicMenu = null;
        static clsMCI cm = null;
        [STAThread]
        static void Main()
        {
            mainMenu = new Menu("主目錄");
            musicMenu = new Menu("音樂列表");
            musicMenu.Ano = "上下箭頭選擇 Enter鍵播放/確認";

            mainMenu.addItem(new MenuItem(1, "錄入音樂",LoadFiles));
            mainMenu.addItem(new MenuItem(2, "查看音樂",ShowFiles));
            mainMenu.addItem(new MenuItem(3, "刪除音樂"));
            mainMenu.addItem(new MenuItem(4, "我的主頁"));
            mainMenu.addItem(new MenuItem(5, "退出登錄",Logout));

            mainMenu.Show();
        }
        static void LoadFiles(MenuItem item)
        {
            FolderBrowserDialog df = new FolderBrowserDialog();
            df.ShowDialog();
            string selectPath =df.SelectedPath;
            if ("" == selectPath) {
                mainMenu.Show();
                return;
            }
            DirectoryInfo dInfo = new DirectoryInfo(selectPath);
            foreach(FileInfo f in dInfo.GetFiles("*.mp3")){
                MusicFileService.Instance().AddFile(new MusicFile(f.Name,f.FullName,f.Length));
            }
            MusicFileService.Instance().Save();
            mainMenu.Show();
        }
        static void ShowFiles(MenuItem item)
        {
            musicMenu.Clear();

            List<MusicFile> files =MusicFileService.Instance().GetAllFiles();
            for (int i = 0; i < files.Count; i++) {
                musicMenu.addItem(new MenuItem(i, files[i].Name, playMusic));
            }
            musicMenu.addItem(new MenuItem(files.Count,"返回主菜單",returnMainMenu));
            musicMenu.addItem(new MenuItem(files.Count + 1, "停止播放", stopPlay));

            musicMenu.Show();
        }
        //播放音樂
        static void playMusic(MenuItem item)
        {
            //MessageBox.Show("播放音樂"+item.Name);
            MusicFile file =MusicFileService.Instance().FindFile(item.Name);
            if (null == file) {
                musicMenu.Show();
                return;
            }
            //停止舊的歌曲
            if (null != cm)
                cm.StopT();
            //播放
            cm = new clsMCI();
            cm.FileName = file.Path;
            cm.play();

            musicMenu.Show();
        }
        //返回主頁面
        static void returnMainMenu(MenuItem item)
        {
            mainMenu.Show();
        }
        //停止播放
        static void stopPlay(MenuItem item)
        {
            if (null != cm)
                cm.StopT();
            musicMenu.Show();
        }
        //退出
        static void Logout(MenuItem item)
        {
        }
    }
}

MusicFile.cs文件內容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MusicDemo
{
    class MusicFile
    {
        public MusicFile(string name, string path, long size)
        {
            this.Name = name;
            this.Path = path;
            this.Size = size;
        }
        public string Name
        {
            set;
            get;
        }
        public string Path
        {
            set;
            get;
        }
        public string Singer
        {
            set;
            get;
        }
        public long Size
        {
            set;
            get;
        }
    }
}

MusicFileService.cs文件內容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace MusicDemo
{
    class MusicFileService
    {

        private MusicFileService() {
            this.InitData();
        }

        //單例模式
        private static MusicFileService T;
        public static MusicFileService Instance() {
            if (T == null)
                T = new MusicFileService();
            return T;
        }

        List<MusicFile> Files = new List<MusicFile>();

        //獲取所有文件
        public List<MusicFile> GetAllFiles()
        {
            return this.Files;
        }
        //新增
        public bool AddFile(MusicFile newFile)
        {
            foreach (MusicFile file in Files)
            {
                if (file.Name == newFile.Name)
                    return false;
            }
            this.Files.Add(newFile);
            return true;
        }
        //根據音樂名稱刪除
        public bool DelFile(string name)
        {
            for (int i = 0; i < this.Files.Count; i++)
            {
                if (this.Files[i].Name ==name)
                {
                    this.Files.RemoveAt(i);
                    return true;
                }
            }
            return false;
        }

        //查找
        public MusicFile FindFile(string name)
        {
            for (int i = 0; i < this.Files.Count; i++)
            {
                if (this.Files[i].Name == name)
                {
                    return this.Files[i];
                }
            }
            return null;
        }
        //寫數據到文件
        public void Save()
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(new FileStream("data1.txt", FileMode.Create));
                foreach (MusicFile file in Files)
                {
                    sw.WriteLine(file.Name + "," + file.Path + "," + file.Size);
                }
            }
            finally
            {

                sw.Close();

            }
        }
        //從文件初始化
        public void InitData()
        {
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(new FileStream("data1.txt", FileMode.OpenOrCreate));
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] datas = line.Split(',');
                    this.Files.Add(new MusicFile(datas[0], datas[1], long.Parse(datas[2])));
                }
            }
            finally
            {
                sr.Close();
            }
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章