[C#]播放內嵌資源檔的MP3

[C#]播放內嵌資源檔的MP3

1.先加入參考 Windows Media Player的COM元件

image

2.程式開頭 加上

using WMPLib;


3.mp3檔案的建置動作改為 內嵌資源

p2

流程:

把資源檔存到stream寫出temp.mp3播放,然後刪除

以下為完整程式碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Reflection;
using WMPLib;
namespace ResourceMP3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            WindowsMediaPlayer wmp = new WindowsMediaPlayer();
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ResourceMP3.tada.mp3"); //命名空間.mp3檔名
            using (Stream output = new FileStream(Path.Combine(Application.StartupPath, "temp.mp3"), FileMode.Create))
            {
                byte[] buffer = new byte[32 * 1024];
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, read);
                }
            }
            wmp.PlayStateChange += new _WMPOCXEvents_PlayStateChangeEventHandler(wmp_PlayStateChange);
            wmp.URL = Path.Combine(Application.StartupPath, "temp.mp3");
            wmp.settings.volume = 100;
            wmp.controls.play();
        }
        void wmp_PlayStateChange(int NewState)
        {
            if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
            {
                this.Close();
            }
        }
        private void Form1_Shown(object sender, EventArgs e)
        {
            if (File.Exists(Path.Combine(Application.StartupPath, "temp.mp3"))==true)
            {
            File.Delete(Path.Combine(Application.StartupPath, "temp.mp3"));
            }
        }
    }
}

ResourceMP3.rar


如有錯誤 歡迎指正