網頁

2011年10月17日 星期一

[C#] 內嵌音樂 單一exe播放


将MP3文件嵌入到exe中并播放


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO; //For FileStream
using System.Runtime.InteropServices; //For DllImport

namespace mp3dll
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        [DllImport("winmm.dll")]
        static extern Int32 mciSendString(String command,
          StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback);
        

        private void Form1_Load(object sender, EventArgs e)
        {

            string path = GetResMp3();
            OpenMedia(path); 
        }
        private string GetResMp3()
        {
            string path = Path.Combine(Application.StartupPath, "Tututu.wav");
            FileStream fs = new FileStream(path, FileMode.Create);
            fs.Write(Properties.Resources.Tututu.wav, 0, Properties.Resources.Tututu.wav.Length);
            fs.Close();
            return path;
        }
        void OpenMedia(string path)
        {
            mciSendString("open " + path + " alias media", null, 0, Handle);
            mciSendString("play media", null, 0, Handle);
        }
        void CloseMedia()
        {
            mciSendString("close all", null, 0, Handle);
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseMedia();
        } 
    }
}

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。