如何:使用平台调用播放波形文件(设备)
更新:2007 年 11 月
下面的代码示例阐释如何在移动设备上使用平台调用 (PInvoke) 播放波形声音文件。
示例
此代码示例使用 PlaySound 在移动设备上播放声音文件。此代码使用 System.Runtime.InteropServices 调用 Compact Framework 的 CoreDll.DLL 的 PlaySound 方法。
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace MobileSoundPInvoke
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu1;
public Form1()
{
InitializeComponent();
PlaySound(".\\sound.wav");
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.Menu = this.mainMenu1;
this.Text = "Form1";
}
#endregion
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
static void Main()
{
Application.Run(new Form1());
}
private enum Flags
{
SND_SYNC = 0x0000,
SND_ASYNC = 0x0001,
SND_NODEFAULT = 0x0002,
SND_MEMORY = 0x0004,
SND_LOOP = 0x0008,
SND_NOSTOP = 0x0010,
SND_NOWAIT = 0x00002000,
SND_ALIAS = 0x00010000,
SND_ALIAS_ID = 0x00110000,
SND_FILENAME = 0x00020000,
SND_RESOURCE = 0x00040004
}
[DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]
private extern static int MobilePlaySound(string szSound, IntPtr hMod, int flags);
public void PlaySound(string fileName)
{
MobilePlaySound(fileName, IntPtr.Zero, (int)(Flags.SND_ASYNC | Flags.SND_FILENAME));
}
}
}
编译代码
在 Visual Studio 中创建一个新的 C# Smartphone 应用程序项目,并将其命名为“MobileSoundPInvoke”。
复制前一示例中的代码,然后在控制台应用程序中,将该代码粘贴至“MobileSoundPInvoke”项目的 Form1.cs 文件中。
可靠编程
- 确保将适当的参数传递给 CMobilePlaySound (string szSound, IntPtr hMod, int flags) 函数,包括 .wav 文件的路径和文件名。
安全性
有关安全的更多信息,请参见 .NET Framework Security(.NET Framework 安全性)。