Sound not playing in my application

心已入冬 提交于 2020-01-06 04:43:25

问题


I am running 1 background process in my application...it continuously checks for some input...When proper input is entered of found..It will play Some wav file..

I have added 1 wav filled named as "ding.wav" into Resources..

and i have written following code in my application... I am using System.Media namespace. and using .Net 4.0

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

but sound is not playing...

Can you tell me what i am doing wrong..!!


回答1:


Try this:

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

You can also try this:

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);
    }
  }
}



回答2:


I think you have to ensure that the file is loaded before you play it.

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



回答3:


I think you need to do more than that. Check out this article.



来源:https://stackoverflow.com/questions/5673065/sound-not-playing-in-my-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!