简体   繁体   English

使用SoundPlayer播放声音

[英]Play a sound using SoundPlayer

I'm trying to play a specific sound. 我正在尝试播放特定的声音。 However I can't seem to reach the file that I added in my Solution Explorer. 但是,我似乎无法访问我在解决方案资源管理器中添加的文件。 (I have this folder called "Sounds/" with several .wav-soundeffects in it) (我有一个名为“Sounds /”的文件夹,里面有几个.wav-soundeffects)

When I hardcode a filepath to a random fixed location on my HDD it works just fine. 当我将文件路径硬编码到我的硬盘上的随机固定位置时,它可以正常工作。 Also when I put my resources in my "bin/debug/"-folder it works just fine (this is the closest I got to a working relative path with the AppDomain.CurrentDomain.BaseDirectory function). 此外,当我将我的资源放在我的“bin / debug /”文件夹中时,它工作正常(这是我最接近AppDomain.CurrentDomain.BaseDirectory函数的工作相对路径)。

How can I make my SoundPlayer work when using the files I added in my Solution Explorer? 在使用我在解决方案资源管理器中添加的文件时,如何使SoundPlayer工作?

You could embed them as a project resource on the dll/exe and then use them through the Application object: 您可以将它们作为项目资源嵌入到dll / exe中,然后通过Application对象使用它们:

Adding and Editing Resources (Visual C#) 添加和编辑资源(Visual C#)

http://msdn.microsoft.com/en-us/library/7k989cfy%28v=vs.90%29.aspx http://msdn.microsoft.com/en-us/library/7k989cfy%28v=vs.90%29.aspx

You could also use the Resource Manager (better option if you want to have your sound files delivered separately): 您也可以使用资源管理器(如果您希望单独提供声音文件,可以使用更好的选项):

Resource Manager 资源经理

http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager%28v=vs.110%29.aspx http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager%28v=vs.110%29.aspx

System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
player.Play();

or You can embed the sound files into your project using resources. 或者您可以使用资源将声音文件嵌入到项目中。

System.Media.SoundPlayer player = new System.Media.SoundPlayer(Resources.Yourfile);
player.Play();

Update: When you add a sound file to the Resources, you can access it by the name of the file. 更新:将声音文件添加到资源时,可以通过文件名访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM