在 Visual Studio 应用程序中播放声音

Play Sounds in a Visual Studio Application

我正在 Visual Studio 2015 (C#) 中制作一个程序,我想为其添加音效。然而,我已经查阅了无数教程,但其中 none 似乎有效,并给了我很多错误。如果有人能给我一个代码来播放资源文件中的 .wav 文件,我将不胜感激

如果你要播放的文件是wav文件,试试这个。

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

How to: Play Sounds in an Application

在button1_Click事件处理程序下添加以下方法代码:

 System.Media.SoundPlayer player = 
 new System.Media.SoundPlayer();
 player.SoundLocation = @"C:\Users\Public\Music\Sample Music\xxxx.wav";
 player.Load();
 player.Play();

我自己写了这个 SounceController,希望对你有帮助:

using System.Windows.Media; // add reference to system.windows.presentation.
using System;
using System.IO;
public class SoundController
{
    private bool isPlaying;
    private MediaPlayer player;

    public SoundController()
    {
        player = new MediaPlayer();
    }
    ~SoundController()
    {
        player = null;
    }

    public void Play(string path)
    {
        if (!File.Exists(path) || isPlaying)
            return;

        isPlaying = true;

        player.Open(new Uri(path));
        player.Play();
    }
    public void Stop()
    {
        if (isPlaying)
        {
            isPlaying = false;
            player.Stop();
        }
    }
}

我推荐你使用 PInvoke 来播放声音 winmm.dll

首先将 System.Runtime.InteropServices 命名空间导入到您的项目中。

using System.Runtime.InteropServices;

那么在你的 class 中你将拥有

[DllImport("winmm.dll")]
static extern Int32 mciSendString(string command, StringBuilder buffer, int bufferSize, IntPtr hwndCallback);

public void Play(string path ,string name)
{
     // Open
     mciSendString($@"open {path} type waveaudio alias {name}", null, 0, IntPtr.Zero);
     // Play
     mciSendString($@"play {name}", null, 0, IntPtr.Zero);
 }

可以播放带名称的wave文件发送正确路径的声音。 .给定名称不需要与 wave file.for 相同的名称示例:

Play(@"C:\soundeffect.wav", "soundEffect1");

通常音效是同时播放的。您可以多次调用此方法来同时播放多个文件。

Play(@"C:\soundeffect1.wav", "soundEffect1");
Play(@"C:\soundeffect2.wav", "soundEffect2");
Play(@"C:\soundeffect3.wav", "soundEffect3");