程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C# MP3播放幫助類

C# MP3播放幫助類

編輯:C#基礎知識
本文為原創文章如需轉載請注明出處:
  /// <summary>
     /// *************************************************
     /// 類名:MP3幫助類
     /// 修改日期:2016/06/25
     /// 作者:董兆生
     /// 聯系方式:評論
     /// *************************************************
     /// </summary>
     public class AudioPlay :IDisposable
     {
         /// <summary>
         /// 播放狀態
         /// </summary>
         private PlayState _palystate = PlayState.Closed;
         public  PlayState PlayState
         {
             set
             {
                 if (value == _palystate) return;
                 OnPropertyChanged(value);
                 _palystate = value;
             }
             get { return _palystate; }
         }
         /// <summary>
         /// 操作錯誤事件
         /// </summary>
         public event Errordelegate EventAudioplayerror;
         /// <summary>
         /// 播放完畢事件
         /// </summary>
         public event PlayEnd EventAudioPlayEnd;
         /// <summary>
         /// 播放狀態發生變化事件
         /// </summary>
         public event DelegatePlayStateChange PlayStatePropertyChanged;
         /// <summary>
         /// 播放時間變化事件
         /// </summary>
         public event DelegatePlayNowTime EventPlayTimeChange;
         /// <summary>
         /// 時間長度毫秒
         /// </summary>
         public readonly StringBuilder PlayLenght = new StringBuilder(255);      
         /// <summary>
         /// 播放音量
         /// </summary>
         private  int _playvlome = 1000;
         public int PlayVolume{get { return _playvlome; }}
         /// <summary>
         /// 當前播放時間
         /// </summary>      
         public int NowPlayTime
         {
             get { return int.Parse(_nowplaytime.ToString()); }
         }
         private readonly StringBuilder _nowplaytime = new StringBuilder(255);
 
         private  AudioModel _nowPlayData;
         /// <summary>
         /// 當前播放歌曲
         /// </summary>
         public AudioModel NowPlayData { get { return _nowPlayData; } }
         /// <summary>
         /// 播放列表
         /// </summary>
         public List<AudioModel> PlayList = new List<AudioModel>();
 
         private int _playindex;
         /// <summary>
         /// 當前播放歌曲在列表中的序號
         /// </summary>
         public int PlayIndex {  get { return _playindex; } }
         /// <summary>
         /// 是否單曲循環播放
         /// </summary>
         public bool IsSingleLoop { set; get; }
         /// <summary>
         /// 是否列表循環播放
         /// </summary>
         public bool IsListLoop { set; get; }
         /// <summary>
         /// 隨機循環播放
         /// </summary>
         public bool IsRandLoop { set; get; }
 
         private Random _random;
 
         public AudioPlay(AudioModel playdata)
         {
             _nowPlayData = (AudioModel)playdata.Clone();
             PlayList .Add(_nowPlayData);       
             _playindex = 0;
    
 
             var playTimer = new Timer
             {
                 Enabled = true,
                 Interval = 1000
             };
 
             playTimer.Tick += playTimer_Tick;
         }
 
         public AudioPlay(List<AudioModel> playList)
         {
             PlayList = new List<AudioModel>(playList);
             _nowPlayData = PlayList[0];          
             _playindex = 0;
 
 
             var playTimer = new Timer
             {
                 Enabled = true,
                 Interval = 1000
             };
             playTimer.Tick += playTimer_Tick;
         }
 
         public bool NextPlay()
         {
             if (PlayList==null) return false;
 
             if (_playindex + 1 >= PlayList.Count) return false;
 
             Closed();
 
             _nowPlayData = PlayList[_playindex + 1];
 
             Open();
 
             SetVolume(PlayVolume);
 
             Play();
 
             _playindex = _playindex + 1;
 
             return true;
         }
 
         public bool PreviousPlay()
         {
             if (PlayList==null) return false;
 
             if (_playindex - 1 <0 ) return false;
 
             Closed();
 
             _nowPlayData = PlayList[_playindex - 1];
 
             Open();
 
             SetVolume(PlayVolume);
 
             Play();
 
             _playindex = _playindex - 1;
 
             return true;
         }
 
         public bool JumpPlay(int index)
         {
             if (PlayList == null) return false;
 
             if (index < 0 && index > PlayList.Count - 1) return false;
 
              Closed();
 
             _nowPlayData = PlayList[index];
 
             Open();
 
             SetVolume(PlayVolume);
 
             Play();
 
             _playindex = index;
 
             return true;
         }
 
         private void playTimer_Tick(object sender, EventArgs e)
         {
             if (PlayState != PlayState.Playing) return;
 
             DoOrder(string.Format("status {0} position", _nowPlayData.AliasMovie), _nowplaytime, _nowplaytime.Capacity);
 
             var returntimeThread = new Thread(ThreadReturnTime) {IsBackground = true};
 
             returntimeThread.Start(_nowplaytime);
 
             if (!_nowplaytime.Equals(PlayLenght)) return;
 
              Closed();
 
             _palystate = PlayState.Closed;
 
             if (EventAudioPlayEnd !=null) EventAudioPlayEnd();
 
             if (IsRandLoop)
             {
 
                 _random = new Random((int)DateTime.Now.Ticks);
 
                 _playindex = _random.Next(0, PlayList.Count);
 
                 _nowPlayData = PlayList[_playindex];
 
                 JumpPlay(_playindex);
 
                 return;
             }
 
             if (IsListLoop)
             {
 
                 if (_playindex + 1 >= PlayList.Count)
                 {
                     _playindex = 0;
                 }
                 else
                 {
                     _playindex = _playindex + 1;
                 }
 
                 _nowPlayData = PlayList[_playindex];
 
                 JumpPlay(_playindex);
 
                 return;
             }
 
             if (!IsSingleLoop) return;
 
             JumpPlay(_playindex);
         }
 
         private void ThreadReturnTime(object time)
         {
             if(_palystate!=PlayState.Playing) return;
 
             if (EventPlayTimeChange != null) EventPlayTimeChange(int.Parse(time.ToString()));
         }
 
    
         /// <summary>
         /// 執行指令
         /// </summary>
         /// <param name="order">指令</param>
         /// <param name="returnString">需要返回的數據</param>
         /// <param name="returnsize">返回數據大小</param>
         /// <returns></returns>
         private bool DoOrder(string order, StringBuilder returnString,int returnsize)
         {
             var error = WinApiHepler.mciSendString(order, returnString, returnsize, new IntPtr());
 
             if(IsDisplsed)return false;
 
             if (error == 0) return true;
 
             Errorlog(error);
 
             return false;
         }
 
         /// <summary>
         /// 事件格式化
         /// </summary>
         /// <param name="millisecond">毫秒</param>
         /// <returns>hh:mm:ss</returns>
         public static string TimeFormat(int millisecond)
         {
             var time = new TimeSpan(0, 0, 0, 0, millisecond);
 
             return string.Format("{0}:{1}:{2}", time.Hours, time.Minutes, time.Seconds);
         }
         /// <summary>
         /// 獲得當前狀態
         /// </summary>
         /// <returns></returns>
         public PlayState GetPlyaState()
         {
             var state = new StringBuilder(50);
 
             return DoOrder(string.Format("status {0} mode", _nowPlayData.AliasMovie), state, state.Capacity) != true ? PlayState.Error : (PlayState)Enum.Parse(typeof(PlayState), state.ToString());
         }
         /// <summary>
         /// 打開音樂文件
         /// </summary>
         public void Open()
         {
             PlayState = DoOrder(string.Format("open {0} alias {1}", _nowPlayData.ShortPath, _nowPlayData.AliasMovie), null, 0) != true ? PlayState.Error : PlayState.Opne;
 
             if (_palystate != PlayState.Opne) return;
 
             DoOrder(string.Format("status {0} length", _nowPlayData.AliasMovie), PlayLenght, PlayLenght.Capacity);
 
         }
         /// <summary>
         /// 播放音樂
         /// </summary>
         /// <param name="starttime">開始時間</param>
         /// <param name="endtime">結束時間</param>
         public void Play(int starttime,int endtime)
         {
             PlayState = DoOrder(string.Format("play {0} from {1} to {2} notify", _nowPlayData.AliasMovie, starttime, endtime), null, 0) != true ? PlayState.Error : PlayState.Playing;         
         }
         /// <summary>
         /// 播放音樂
         /// </summary>
         public void Play()
         {
             PlayState = DoOrder(string.Format("play {0} notify", _nowPlayData.AliasMovie), null, 0) != true ? PlayState.Error : PlayState.Playing;
         }
         /// <summary>
         /// 暫停
         /// </summary>
         public void Pause()
         {
             PlayState = DoOrder(string.Format("pause {0}", _nowPlayData.AliasMovie), null, 0) != true ? PlayState.Error : PlayState.Paused;
         }
         /// <summary>
         /// 停止
         /// </summary>
         public void Stop()
         {
             PlayState = DoOrder(string.Format("stop {0}", _nowPlayData.AliasMovie), null, 0) != true ? PlayState.Error : PlayState.Stopped;         
         }
         /// <summary>
         /// 關閉音樂
         /// </summary>
         public void Closed()
         {
             PlayState = DoOrder(string.Format("close {0}", _nowPlayData.AliasMovie), null, 0) != true ? PlayState.Error : PlayState.Closed;      
         }
         /// <summary>
         /// 設置音量
         /// </summary>
         /// <param name="volume">0-1000</param>
         /// <returns></returns>
         public  bool SetVolume(int volume)
         {
             if (!DoOrder(string.Format("setaudio {0} volume to {1}", _nowPlayData.AliasMovie, volume), null, 0))
                 return false;
             _playvlome = volume;
             return true;
         }
 
         private void Errorlog(int error)
         {
             var errorText = new StringBuilder(50);
 
             WinApiHepler.mciGetErrorString(error, errorText, errorText.Capacity);
 
             if (EventAudioplayerror == null) return;
 
             EventAudioplayerror(errorText.ToString());
         }
 
         private void OnPropertyChanged(PlayState state)
         {
             if (PlayStatePropertyChanged != null)
             {
                 PlayStatePropertyChanged(state);
             }
         }
 
        protected bool IsDisplsed { get; set; }
 
        ~AudioPlay()
         {
             Dispose();
         }
  
         /// <summary>
         /// 釋放
         /// </summary>
         public void Dispose()
         {
             Dispose(IsDisplsed);
         }
         public virtual void Dispose(bool isDisplsed)
         {
             if (isDisplsed)
                 return;
                
             EventAudioplayerror = null;
 
             EventAudioPlayEnd = null;
 
             EventPlayTimeChange = null;
 
             DoOrder(string.Format("close {0}", _nowPlayData.AliasMovie), null, 0);        
         }
      
     }
     public delegate void Errordelegate(string error);
 
     public delegate void PlayEnd();
 
     public delegate void DelegateHockMesg(Message msg);
 
     public delegate void DelegatePlayStateChange(PlayState state);
 
     public delegate void DelegatePlayNowTime(int time);
 
     public class WindosMessageInform :UserControl
     {
         int[] HockMsg { set; get; }
 
         public event DelegateHockMesg EventHockmesg;
 
         public WindosMessageInform(int[] hockmsg)
         {
             HockMsg = hockmsg;
         }
 
         protected override void WndProc(ref Message m)
         {
             if (HockMsg.ToList().Contains(m.Msg))
             {
                 if (EventHockmesg != null) EventHockmesg(m);
             }
             base.WndProc(ref m);
         }
     }
 
     public class AudioModel : ICloneable
     {
         public AudioModel()
         {
           
         }
 
         public AudioModel(string file,string alias,object data)
         {
             PlayFile = file;
 
             AliasMovie = alias;
 
             SourceData = data;
 
             FileName = System.IO.Path.GetFileNameWithoutExtension(file);
 
             var shortpath = new StringBuilder(255);
 
             WinApiHepler.GetShortPathName(PlayFile, shortpath, shortpath.Capacity);
 
             ShortPath = shortpath.ToString();
         }  
         public string FileName { set; get; }
        
         public string PlayFile { set; get; }
 
         public string ShortPath { set; get; }
 
         public string AliasMovie { set; get; }
 
         public object SourceData { set; get; }
 
         public object Clone()
         {
             var clonedata = SerializationHelper.GetSerialization(this);
 
             return SerializationHelper.ScriptDeserialize<AudioModel>(clonedata);
         }
     }
 
     public enum PlayState
     {
         Opne,
         Playing,
         Paused,
         Stopped,
         Closed,
         None,
         Error
     }
AudioPlayHelper

基於winAPI winmm.dll  

mciSendString 編寫的幫助類功能比較齊全(起碼比我現在網上搜的齊全@-@)

已經實現的功能 播放 暫停 停止 關閉就不多說了基本功能沒啥好說的。

事件:播放完畢通知,時間變化通知,狀態變化通知,錯誤通知

功能:上一首, 下一首 ,指定順序播放

播放後狀態:單曲循環,列表循環,隨機播放

 

裡面用到的BearChildren為我個人編寫的工具功能如名字一樣熊孩子...意思:讓這個框架跟熊孩子一樣什麼都能做 目前還在完善中 

目前框架主要是以單機桌面開發編寫的一套工具,內容為圖像處理,Io,數據等,我希望能有更多的人來幫助我來完善這個框架在日常工作中讓開發變的更加方便快捷,

QQ群為:572582327 歡迎大家一起加入討論豐富自己的技術 無論你是大神還是新手都歡迎你們。

 

代碼下載鏈接:自帶播放器demo

https://git.coding.net/BearChildren/AudioPlayHelper.git

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved