簡體   English   中英

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

[英]Playing sounds on Console - 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",
};

確保將文件屬性設置為:

構建動作 - 內容

復制到輸出目錄 - 如果更新則復制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM