Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用C从Properties.Resources播放WAV文件#_C#_Wav - Fatal编程技术网

C# 如何使用C从Properties.Resources播放WAV文件#

C# 如何使用C从Properties.Resources播放WAV文件#,c#,wav,C#,Wav,如何从Properties.Resources播放wav文件 我尝试了一些代码,但每次我的Priperties.Resource.myFile都将我放入byte[]但我的代码需要string路径,而不是byte[]数组 System.Media.SoundPlayer player = new System.Media.SoundPlayer(); player.SoundLocation = @"myFile.wav"; player.Play(); 我不想使用临时

如何从
Properties.Resources
播放wav文件

我尝试了一些代码,但每次我的
Priperties.Resource.myFile
都将我放入
byte[]
但我的代码需要
string
路径,而不是
byte[]
数组

    System.Media.SoundPlayer player = new System.Media.SoundPlayer();

    player.SoundLocation = @"myFile.wav";
    player.Play();
我不想使用临时文件。是否可以直接从资源中进行播放

谢谢你的建议


那么,我可以从资源中播放WAV文件吗

您可以像这样使用
属性:

System.Media.SoundPlayer player = new System.Media.SoundPlayer();

player.Stream = new MemoryStream(data);
player.Play();
System.Media.SoundPlayer player = new System.Media.SoundPlayer();

player.Stream = Properties.Resources.myFile;
player.Play();
其中
data
是从资源文件中获取的
字节[]

更新:

Properties.Resources.myFile
实际上应该是一个流,所以直接像这样使用它:

System.Media.SoundPlayer player = new System.Media.SoundPlayer();

player.Stream = new MemoryStream(data);
player.Play();
System.Media.SoundPlayer player = new System.Media.SoundPlayer();

player.Stream = Properties.Resources.myFile;
player.Play();

据我所知,有两种方法可以做到这一点,见下文:

  • 使用文件路径
    首先将文件放在项目的根文件夹中,然后无论您在
    Debug
    Release
    模式下运行程序,都可以确保访问文件

        var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
        SoundPlayer player = new SoundPlayer();
        player.SoundLocation = Path.Combine(basePath, @"./../../Reminder.wav");
        player.Load();
        player.Play();
    
  • 使用资源
    按照下面的动画,将“现有文件”添加到项目中

  • 这种方式的优点是:

    运行程序时,只需复制“bin”目录下的文件夹“Release”。

    SoundPlayer只能播放wav文件。因此,我可以从资源中播放wav文件吗?如果这是您想要的。请将您的问题改为提及WAV文件而不是MP3,这样不会让其他人感到困惑。我尝试了您的代码,但在
    newmemoryStream(data)上我收到一个错误
    无法从'System.IO.UnmanagedMemoryStream'转换为'int'
    。其中
    数据
    属性.Resources.myFile
    。我的文件是wav。谢谢你的帮助。工作完美。