读书人

winForm 声音怎么实现

发布时间: 2011-12-14 23:20:17 作者: rapoo

winForm 声音如何实现
想要实现类似於QQ一样,有消息时,便有预设的声音发出,如何实现

注:是vs2003.

[解决办法]
INVOKE API
[解决办法]
using System;
using System.Runtime.InteropServices;

public class SoundPlayer
{
public SoundPlayer()
{
}
[DllImport( "winmm.dll ")]
private static extern long sndPlaySound(string lpszSoundName, long uFlags);

public static void PlaySound(string fileName)
{
sndPlaySound(fileName, 1);
}
}
[解决办法]
用循环监控貌似有点笨。哈哈
[解决办法]
除了API,没有更好的法子

[解决办法]
API函数
[DllImport( "winmm.dll ", EntryPoint= "PlaySound ")]
public static extern int PlaySound (
string lpszName,
int hModule,
int dwFlags
);
[解决办法]
using System.Media;

private void button1_Click(object sender, EventArgs e)
{
//通过文件播放
SoundPlayer vSoundPlayer = new SoundPlayer();
vSoundPlayer.Stream = new FileStream(@ "C:\WINDOWS\Media\chord.wav ",
FileMode.Open, FileAccess.Read);
vSoundPlayer.Play();
}
[解决办法]
获取事件
然后调用API 播放声音文件。
[解决办法]
using System.Media;

private void button1_Click(object sender, EventArgs e)
{
//通过文件播放
SoundPlayer vSoundPlayer = new SoundPlayer();
vSoundPlayer.Stream = new FileStream(@ "C:\WINDOWS\Media\chord.wav ",
FileMode.Open, FileAccess.Read);
vSoundPlayer.Play();
}


这个方法可行。你可以试试。
[解决办法]
vs2005下可用
using System.Media;

private void button1_Click(object sender, EventArgs e)
{
SoundPlayer vSoundPlayer = new SoundPlayer();
vSoundPlayer.Stream = new FileStream(@ "C:\WINDOWS\Media\chord.wav ",
FileMode.Open, FileAccess.Read);
vSoundPlayer.Play();
}
vs2003下只能用api了
[解决办法]
源代码如下(全部)(自己实现的播放声音类):

public sealed class wavPlayer
{
[DllImport( "Winmm ")]
public static extern bool PlaySound(string pszSound, IntPtr hmod, UInt32
fdwSound);
private const Int32 m_SND_ASYNC = 1;
private const Int32 m_SND_LOOP = 8;
private const Int32 m_SND_FILENAME = 131072;
private static string m_PathSoundFile = string.Empty;
private static bool m_State = false;

public static bool PlayState
{
set
{
m_State = value;
}
get
{
return m_State;
}
}

public static void InitSound()
{
string soundFile = ConfigurationManager.AppSettings[ "SoundFile "].ToString();

if (soundFile == " ")


{
m_PathSoundFile = AppDomain.CurrentDomain.BaseDirectory + @ "\notify2.wav ";
}
else
{
m_PathSoundFile = soundFile;
}
}

static wavPlayer()
{
string soundFile = ConfigurationManager.AppSettings[ "SoundFile "].ToString();

if (soundFile == " ")
{
m_PathSoundFile = AppDomain.CurrentDomain.BaseDirectory + @ "\notify.wav ";
}
else
{
m_PathSoundFile = soundFile;
}
}

public static void Play()
{
if (PlayState == false)
{
PlaySound(m_PathSoundFile, IntPtr.Zero, m_SND_ASYNC | m_SND_LOOP | m_SND_FILENAME);
PlayState = true;
}
}

public static void Stop()
{
if (PlayState == true)
{
PlaySound(null, IntPtr.Zero, m_SND_ASYNC);
PlayState = false;
}
}
}
[解决办法]
vs2003用Api也有问题
干脆用madie player控件

读书人网 >C#

热点推荐