ตอนที่ทำ NSC วันก่อน ต้องเอาเพลงมาใส่ใน form เลยลองหาวิธีการนำ mp3 มาใช้ดู ก็ทำได้ดังนี้
ขั้นแรกก็เหมือนเดิมคือ สร้าง form มาสักอันหนึ่ง
จากนั้นให้สร้าง class ขึ้นมาอีกอัน ในที่นี้ให้ชื่อ MP3
ซึ่งมีโค้ดดังนี้
class MP3
{
private string _command;
private bool isOpen;
[DllImport("winmm.dll")]
private static extern long mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);
public void Close()
{
_command = "close MediaFile";
mciSendString(_command, null, 0, IntPtr.Zero);
isOpen = false;
}
public void Open(string sFileName)
{
_command = "open \"" + sFileName + "\" type mpegvideo alias MediaFile";
mciSendString(_command, null, 0, IntPtr.Zero);
isOpen = true;
}
public void Play(bool loop)
{
if (isOpen)
{
_command = "play MediaFile";
if (loop)
_command += " REPEAT";
mciSendString(_command, null, 0, IntPtr.Zero);
}
}
}ซึ่งจะมีทั้งหมด 3 method ด้วยกัน คือ
1.Open ไว้ใส่ path ของเพลงที่ต้องการจะเล่น
2.Play เอาไว้เล่น ซึ่งจะให้ใส่ bool ว่าจะเล่นซ้ำหรือไม่ ถ้าเล่นซ้ำใส่ true ถ้าไม่ก็ false
3.Close เอาไว้จบเพลง
ซึ่งการใช้ DllImport นั้นจะต้อง using System.Runtime.InteropServices; ด้วย
วีธีการใช้
ขั้นแรกประกาศตัวแปรขึ้นมา
ต่อมาให้ใช้ method Open เช่น
mp3.Open("D://download//I_Do_Thai_version.mp3");
จะนั้นก็เรียกใช้ method play ถ้าอยากให้เริ่มดังตั้งแต่แรกก็ให้เรียก Play ใน Form_Load ของ form นั้นๆ
ซึ่งก็ไม่ยากเลยใช่รึป่าวครับ ^^
credit: http://www.geekpedia.com/code111_Play-MP3-Files-Using-Csharp.html
Last 5 posts by zephiroth
- chowwoyzz,,How to create DB in SAP - April 27th, 2010
- ทำไมสร้าง folder ชื่อ con ไม่ได้อะ?? - January 7th, 2010
- ใช้ตาเล่นเกมแทนมือ - January 6th, 2010
- [C#]การรับ fscommand จาก flash - January 2nd, 2010
- [C#]Disble Right Click by C-S - January 2nd, 2010
