I'm writing a Console application on C# and I want to play a sound when I display texts continuously. This is what I've done :
static SoundPlayer typewriter = new SoundPlayer("typewriter");
static public void print(string str, int delay)
{
Thread skipThread = new Thread(skipText);
typewriter.PlayLooping();
textgap = delay;
foreach (char c in str)
{
Console.Write(c);
if (textgap != 0)
Thread.Sleep(textgap);
}
typewriter.Stop();
}
typewriter.wav
is imported to my project next to the .cs
files and I've selected copy always
. When I run this code, an error pops out when starting playing the sound saying Please be sure a sound file exists at the specified location.
What is wrong here?
EDIT : Changed my code to the following according to Kevin J's answer.
static SoundPlayer typewritter;
public static void Load()
{
Assembly assembly;
assembly = Assembly.GetExecutingAssembly();
typewritter = new SoundPlayer(assembly.GetManifestResourceStream
("typewriter"));
}
I also should precised to use the path Environment.CurruntDirectory + "typewriter"
but nothing changes.
Figured out the problem : I just needed to set the SoundLocation
property of the SoundPlayer
instance :
SoundPlayer typewriter = new SoundPlayer();
typewriter.SoundLocation = Environment.CurrentDirectory + "/typewriter.wav";
Here's something that might help you out (please note that this code is for a winforms app, but you should be able to convert to a console app. Just study the code to see how it works) You'll basically be adding the .wav file as a 'resource' to your program. Then, your program can access the .wav file and play it:
using System.Reflection;
using System.IO;
using System.Resources;
using System.Media;
using System.Diagnostics;
namespace Yournamespace
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Assembly assembly;
Stream soundStream;
SoundPlayer sp;
assembly = Assembly.GetExecutingAssembly();
sp = new SoundPlayer(assembly.GetManifestResourceStream
("Yournamespace.Dreamer.wav"));
sp.Play();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With