5

我正在 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",但没有任何变化。

4

3 回答 3

5

发现了问题:我只需要设置实例的SoundLocation属性:SoundPlayer

SoundPlayer typewriter = new SoundPlayer();
typewriter.SoundLocation = Environment.CurrentDirectory + "/typewriter.wav";
于 2014-02-26T02:22:36.617 回答
3

这里有一些可能对您有所帮助(请注意,此代码适用于 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();  
        } 
    }
}
于 2014-02-25T23:59:41.763 回答
0

例如,如果您的声音在文件夹“Assets”中,那么子文件夹“SoundClips”会这样做。

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

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

确保您将文件属性设置为:

构建动作 - 内容

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

于 2018-10-31T15:34:45.670 回答