Playing sounds on Console - C#

强颜欢笑 提交于 2019-11-30 23:48:31
user26830

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

Here's something that might help you out (please note that this code is for a winforms app, but you should be able to convert to a console app. Just study the code to see how it works) You'll basically be adding the .wav file as a 'resource' to your program. Then, your program can access the .wav file and play it:

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

If for example you have your sounds in the folder "Assets" then subfolder "SoundClips" do it like this.

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

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

Make sure you have the file properties set to:

build action - Content

copy to output directory - Copy if newer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!