C# 音頻操作系統項目總結

openkk 12年前發布 | 49K 次閱讀 C# .NET開發

此項目需求是針對.wav格式音頻進行操作,轉換成相應的.mp3格式的音頻文件,對音頻進行切割,最后以需求的形式輸出,此篇會回顧運用到的一些知識點。

1.MDI子窗口的建立:

首先一個窗體能夠創建多個MDI窗體,應當將IsMDIContainer屬性設為true;以下為效果圖:

C# 音頻操作系統項目總結

控制窗體切換的是一個DotNetBar.TabStrip控件,style屬性為Office2007Document,TabLayOutType:FixedWithNavigationBox

創建窗體的代碼如下:

    ///   
    /// 創建MDI子窗體類  
    ///   
    class CreateMDIWindow  
    {  
         ///   
        /// 當前程序的主窗體對象  
        ///   
        public static Form MainForm { get; set; }  

        ///   
        /// 創建子窗口  
        ///   
        /// 
        窗口類型
          
        public static void CreateChildWindow
        () where T : Form, new()  
        // where 子句還可以包括構造函數約束。 可以使用 new 運算符創建類型參數的實例;但類型參數為此必須受構造函數約束   
        // new() 的約束。 new() 約束可以讓編譯器知道:提供的任何類型參數都必須具有可訪問的無參數(或默認)構造函數。             
        {  
            T form = null;  

            var childForms = MainForm.MdiChildren;  
            //遍歷窗體  
            foreach (Form f in childForms)  
            {  
                if (f is T)  
                {  
                    form = f as T;  
                    break;  
                }  
            }  
            //如果沒有,則創建  
            if (form == null)  
            {  
                //新建窗體  
                form = new T();  
                //設定窗體的圖標  
                form.Icon = System.Drawing.Icon.FromHandle(Properties.Resources.MainIcon.GetHicon());  
                //設定窗體的主圖標  
                form.MdiParent = MainForm;  
                //設定窗體的邊框類型  
                form.FormBorderStyle = FormBorderStyle.FixedToolWindow;  
            }  
            //窗口如何顯示  
            form.WindowState = FormWindowState.Maximized;  
            form.Show();  
        }  
    }  
   

前臺點擊按鈕調用代碼:CreateMDIWindow.CreateChildWindow ();  <>里為窗體的名稱。

2.序列化與反序列化:

當一個系統你有默認的工作目錄,默認的文件保存路徑,且這些數據時唯一的,你希望每次打開軟件都會顯示這些數據,也可以更新這些數據,可以使用序列化與反序列化。

C# 音頻操作系統項目總結

我們以項目存儲根目錄和選擇項目為例:

代碼如下:

    [Serializable]  
    public  class UserSetting  
    {  
        ///   
        /// 序列化存儲路徑  
        ///   
        private string FilePath{ get { return Path.Combine(Environment.CurrentDirectory, "User.data"); } }  

        ///   
        /// 音頻資源存儲目錄  
        ///   
        public  string AudioResourceFolder { get; set; }  

        ///   
        /// 項目名稱  
        ///   
        public string Solution { get; set; }  

        ///   
        /// 構造函數,創建序列化存儲文件  
        ///   
        public UserSetting()  
        {  
            if (!File.Exists(FilePath))  
            {  
                FileStream fs = File.Create(FilePath);  
                fs.Close();//不關閉文件流,首次創建該文件后不能被使用買現成會被占用  
            }        
        }  

        ///   
        /// 通過反序列化方法,獲得保存的數據  
        ///         
        public UserSetting ReadUserSetting()         
        {  
            using (FileStream fs = new FileStream(FilePath, FileMode.Open,FileAccess.Read))  
            {  
                object ob = null;  
                if (fs.Length > 0)  
                {  
                    SoapFormatter sf = new SoapFormatter();  
                    ob = sf.Deserialize(fs);                    
                }  
                return ob as UserSetting;  
            }  
        }  

        ///   
        /// 通過序列化方式,保存數據  
        ///         
        public void SaveUserSetting(object obj)  
        {  
            using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write))  
            {  
                SoapFormatter sf = new SoapFormatter();  
                sf.Serialize(fs,obj);  
            }  
        }  

    }  

3.Datagridview動態生成:

C# 音頻操作系統項目總結

根據設置的樓層生成相應樓層帶button按鈕的datagridview,并且每層按鈕為每層選定選擇音樂,代碼如下:

    ///   
    /// 綁定樓層音樂屬性  
    ///   
    private void BindData(int elevatorLow,int number)  
    {  
        try  
        {  
            DataTable list = new DataTable();  
            list.Columns.Clear();  
            list.Columns.Add(new DataColumn("name", typeof(string)));  
            list.Columns.Add(new DataColumn("musicPath", typeof(string)));               
            for (int i =0; i < number; i++)  
            {  
                //不包括樓層0層  
                if (elevatorLow != 0)  
                {  
                    list.Rows.Add(list.NewRow());  
                    list.Rows[i][0] = elevatorLow;  
                }  
                else { i--; }  
                elevatorLow++;  
            }  
            dataGridViewX1.DataSource = list;  
        }  
        catch (Exception ex)  
        { MessageBox.Show(ex.ToString()); }  
    }  
選擇音樂按鈕事件:
    private void dataGridViewX1_CellContentClick(object sender, DataGridViewCellEventArgs e)  
    {  
        try  
        {           
            //點擊選擇按鈕觸發的事件  
            if (e.RowIndex >= 0)  
            {  
                DataGridViewColumn column = dataGridViewX1.Columns[e.ColumnIndex];  
                if (column is DataGridViewButtonColumn)  
                {  
                    OpenFileDialog openMusic = new OpenFileDialog();  
                    openMusic.AddExtension = true;  
                    openMusic.Multiselect = true;  
                    openMusic.Filter = "MP3文件(*.mp3)|*mp3";                     
                    if (openMusic.ShowDialog() == DialogResult.OK)  
                    {  
                        dataGridViewX1.Rows[e.RowIndex].Cells[2].Value = Path.GetFileName(openMusic.FileName);                         
                    }  
                }  
            }  
        }  
        catch(Exception ex)  
        { MessageBox.Show(ex.ToString()); }  
    }  
4.獲得音樂文件屬性:

使用Shellclass獲得文件屬性可以參考  點擊打開鏈接   

C# 音頻操作系統項目總結

代碼如下:

    ///   
    /// 獲得音樂長度  
    ///   
    /// 文件的完整路徑  
    public static string[] GetMP3Time(string filePath)  
    {  
        string dirName = Path.GetDirectoryName(filePath);  
        string SongName = Path.GetFileName(filePath);//獲得歌曲名稱             
        ShellClass sh = new ShellClass();  
        Folder dir = sh.NameSpace(dirName);  
        FolderItem item = dir.ParseName(SongName);  
        string SongTime = dir.GetDetailsOf(item, 27);//27為獲得歌曲持續時間 ,28為獲得音樂速率,1為獲得音樂文件大小      
        string[] time = Regex.Split(SongTime, ":");  
        return time;  
    }  

5.音頻操作:

音頻的操作用的fmpeg.exe ,下載地址

fmpeg放在bin目錄下,代碼如下:
    ///   
    /// 轉換函數  
    ///   
    /// ffmpeg程序  
    /// 執行參數       
    public static void ExcuteProcess(string exe, string arg)  
    {  
        using (var p = new Process())  
        {               
                p.StartInfo.FileName = exe;  
                p.StartInfo.Arguments = arg;  
                p.StartInfo.UseShellExecute = false;    //輸出信息重定向  
                p.StartInfo.CreateNoWindow = true;  
                p.StartInfo.RedirectStandardError = true;  
                p.StartInfo.RedirectStandardOutput = true;  
                p.Start();                    //啟動線程  
                p.BeginOutputReadLine();  
                p.BeginErrorReadLine();  
                p.WaitForExit();//等待進程結束                                        
        }  
    }  
音頻轉換的代碼如下:
    private void btnConvert_Click(object sender, EventArgs e)  
    {  
        //轉換MP3  
        if (txtMp3Music.Text != "")  
        {  
            string fromMusic = Statics.Setting.AudioResourceFolder + "\\" + Statics.Setting.Solution+"\\" + cobFolders.Text + "\\" + txtMusic.Text;//轉換音樂路徑  
            string toMusic = Statics.Setting.AudioResourceFolder + "\\" + Statics.Setting.Solution+"\\" + cobFolders.Text + "\\" + txtMp3Music.Text;//轉換后音樂路徑  
            int bitrate = Convert.ToInt32(cobBitRate.Text) * 1000;//恒定碼率  
            string Hz = cobHz.Text;//采樣頻率  

            try  
            {  
                MP3Convertion.ExcuteProcess("ffmpeg.exe", "-y -ab " + bitrate + " -ar " + Hz + " -i \"" + fromMusic + "\" \"" + toMusic + "\"");  
                if (cbRetain.Checked == false)  
                {  
                    File.Delete(fromMusic);  
                    BindList();  
                }  
                else  
                {  
                    foreach (ListViewItem lt in listMusics.Items)  
                    {  
                        if (lt.Text == txtMusic.Text)  
                        {  
                            listMusics.Items.Remove(lt);  
                        }  
                    }  
                }  

                //轉換完成  
                MessageBox.Show("轉換完成");  
                txtMusic.Text = "";  
                txtMp3Music.Text = "";  
            }  
            catch (Exception ex)  
            { MessageBox.Show(ex.ToString()); }  
        }  
        else  
        {  
            MessageBox.Show("請選擇你要轉換的音樂");   
        }  
    }  
音頻切割的代碼如下:
    private void btnCut_Click(object sender, EventArgs e)  
    {  
        SaveFileDialog saveMusic = new SaveFileDialog();  
        saveMusic.Title = "選擇音樂文件存放的位置";  
        saveMusic.DefaultExt = ".mp3";  
        saveMusic.InitialDirectory = Statics.Setting.AudioResourceFolder +"\\"  + Statics.Setting.Solution+"\\" + cobFolders.Text;  
        string fromPath = Statics.Setting.AudioResourceFolder + "\\" + Statics.Setting.Solution +"\\"+ cobFolders.Text + "\\" + txtMusic.Text;//要切割音樂的物理路徑  
        string startTime = string.Format("0:{0}:{1}", txtBeginM.Text, txtBeginS.Text).Trim();//歌曲起始時間  
        int duration = (Convert.ToInt32(this.txtEndM.Text) * 60 + Convert.ToInt32(this.txtEndS.Text)) - (Convert.ToInt32(this.txtBeginM.Text) * 60 + Convert.ToInt32(this.txtBeginS.Text));  
        string endTime = string.Format("0:{0}:{1}", duration / 60, duration % 60);//endTime是持續的時間,不是歌曲結束的時間  
        if (saveMusic.ShowDialog() == DialogResult.OK)  
        {  
            string savePath = saveMusic.FileName;//切割后音樂保存的物理路徑  
            try  
            {  
                MP3Convertion.ExcuteProcess("ffmpeg.exe", "-y -i \"" + fromPath + "\" -ss " + startTime + " -t " + endTime + " -acodec copy \"" + savePath+"\"");//-acodec copy表示歌曲的碼率和采樣頻率均與前者相同  
                MessageBox.Show("已切割完成");  
            }  
            catch (Exception ex)  
            {  
                MessageBox.Show(ex.ToString());  
            }                 
        }  
    }  
切割音頻操作系統的知識點就總結道這了,就是fmpeg的應用。

轉自:http://blog.csdn.net/kaoleba126com/article/details/7570745

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!