Kishan Gajjar
Kishan Gajjar

Reputation: 1138

Sound not playing in my application

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..!! enter image description here

Upvotes: 1

Views: 4646

Answers (3)

RB1
RB1

Reputation: 1

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

Upvotes: 0

jfs
jfs

Reputation: 16778

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

Upvotes: 1

Marco
Marco

Reputation: 57583

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

Upvotes: 2

Related Questions