在控制台上播放声音 – C#
我正在C#上编写一个Console应用程序,我希望在连续显示文本时播放声音。 这就是我所做的:
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
选择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";
这里有些东西可以帮助你(请注意这个代码适用于winforms应用程序,但你应该能够转换为控制台应用程序。只需研究代码以了解它是如何工作的)你基本上会添加.wav将文件作为程序的“资源”。 然后,您的程序可以访问.wav文件并播放它:
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(); } } }
例如,如果您在“资产”文件夹中有声音,那么子文件夹“SoundClips”会这样做。
var soundLocation = Environment.CurrentDirectory + @"\Assets\SoundClips\"; SoundPlayer player = new SoundPlayer { SoundLocation = soundLocation + "typewriter.wav", };
确保将文件属性设置为:
构建动作 – 内容
复制到输出目录 – 如果更新则复制