在控制台上播放声音-C# [英] Playing sounds on Console - C#

查看:243
本文介绍了在控制台上播放声音-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C#上编写控制台应用程序,我想在连续显示文本时播放声音.这就是我所做的:

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导入到.cs文件旁边的项目中,并且我选择了copy always.当我运行此代码时,开始播放说Please be sure a sound file exists at the specified location.的声音时会弹出错误消息 怎么了?

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?

根据Kevin J的回答,将我的代码更改为以下代码.

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

我还应该精确使用路径Environment.CurruntDirectory + "typewriter",但不会发生任何变化.

I also should precised to use the path Environment.CurruntDirectory + "typewriter" but nothing changes.

推荐答案

解决了这个问题:我只需要设置SoundPlayer实例的SoundLocation属性:

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";

这篇关于在控制台上播放声音-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆