声音没有在我的应用程序中播放

时间:2011-04-15 06:18:42

标签: c# .net .net-4.0 windows

我在我的应用程序中运行了1个后台进程...它不断检查输入...当输入找到正确的输入时..它将播放一些wav文件..

我在资源中添加了1个名为“ding.wav”的wav ..

我在我的申请中写了以下代码...... 我正在使用System.Media命名空间。并使用.Net 4.0

SoundPlayer player = new SoundPlayer();
player.Stream = Properties.Resources.ding;
player.Play();

但声音没有播放......

你能告诉我我做错了什么.. !! enter image description here

3 个答案:

答案 0 :(得分:2)

试试这个:

SoundPlayer player = new SoundPlayer(Properties.Resources.ding);
player.Play();

你也可以试试这个:

using System;
using System.Runtime.InteropServices;
using System.Resources;
using System.IO;
namespace Win32
{
  public class Winmm
  {
    public const UInt32 SND_ASYNC = 1;
    public const UInt32 SND_MEMORY = 4;

    [DllImport("Winmm.dll")]
    public static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags);
    public Winmm() { }
    public static void PlayWavResource(string wav)
    {
      // get the namespace 
      string strNameSpace= 
        System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();

      // get the resource into a stream
      Stream str = 
        System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(      strNameSpace +"."+ wav );
      if ( str == null ) return;
     // bring stream into a byte array
     byte[] bStr = new Byte[str.Length];
     str.Read(bStr, 0, (int)str.Length);
     // play the resource
     PlaySound(bStr, IntPtr.Zero, SND_ASYNC | SND_MEMORY);
    }
  }
}

答案 1 :(得分:1)

我认为你必须确保在播放之前加载文件。

SoundPlayer player = new SoundPlayer(Properties.Resources.ding);
player.Load();
player.Play();

答案 2 :(得分:0)

我认为你需要做的更多。查看this文章。