我正在用 C# 编写一个控制台应用程序,我想在连续显示文本时播放声音。这就是我所做的:
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
被导入到我的项目中,位于 .cs
文件旁边,我选择了 copy always
。当我运行这段代码时,开始播放声音时会弹出一个错误提示 Please be sure a sound file exists at the specified location.
这里有什么问题?
编辑: 根据 Kevin J 的回答,将我的代码更改为以下内容。
static SoundPlayer typewritter;
public static void Load()
{
Assembly assembly;
assembly = Assembly.GetExecutingAssembly();
typewritter = new SoundPlayer(assembly.GetManifestResourceStream
("typewriter"));
}
我还应该精确地使用路径 Environment.CurruntDirectory + "typewriter"
但没有任何变化。
最佳答案
解决了问题:我只需要设置 SoundPlayer
实例的 SoundLocation
属性:
SoundPlayer typewriter = new SoundPlayer();
typewriter.SoundLocation = Environment.CurrentDirectory + "/typewriter.wav";
关于c# - 在控制台上播放声音 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22028688/