在控制台上播放声音 - C#

时间:2014-02-25 23:42:57

标签: c# audio console console-application soundplayer

我正在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。当我运行此代码时,在开始播放声音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",但没有任何改变。

3 个答案:

答案 0 :(得分:3)

找出问题:我只需要设置SoundLocation实例的SoundPlayer属性:

SoundPlayer typewriter = new SoundPlayer();
typewriter.SoundLocation = Environment.CurrentDirectory + "/typewriter.wav";

答案 1 :(得分:2)

这里有些东西可以帮助你(请注意这个代码适用于winforms应用程序,但你应该能够转换为控制台应用程序。只需研究代码以了解它是如何工作的)你基本上会添加.wav文件作为程序的“资源”。然后,您的程序可以访问.wav文件并播放它:

enter image description here

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

答案 2 :(得分:0)

例如,如果您的声音位于“资产”文件夹中,则子文件夹“ SoundClips”就是这样。

var soundLocation = Environment.CurrentDirectory + @"\Assets\SoundClips\";

SoundPlayer player = new SoundPlayer
{
    SoundLocation = soundLocation + "typewriter.wav",
};

确保将文件属性设置为:

构建操作-内容

复制到输出目录-如果较新则复制