开发者

Sound not playing in my application

开发者 https://www.devze.com 2023-02-25 11:59 出处:网络
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 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..!!

Sound not playing in my application


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


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


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


For me (VS 2022, .net 6, C # 10) it worked:

  1. Import the "ding.wav" file into the main directory.

  2. Change in: Properties (ding.wav) - Copy to Output Directory to: Copy always. Later it was enough to:

     SoundPlayer player = new SoundPlayer("ding.wav");
     player.Load ();
     player.Play ();
    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号