简体   繁体   中英

How do you play sound in C#?

I've tried this but I'm interested in playing sound from where my program starts. Such I have the .wav file inside of the project folder.

   SoundPlayer simpleSound = new SoundPlayer(@"/yay.wav");
    simpleSound.Play();

Thank you

Such I have the .wav file inside of the project folder.

This is probably your problem.

When you compile your application, it doesn't end up straight in the project folder - it ends up in a subdirectory (either /Debug/bin or /Release/bin ). Put the wav file there instead of in the project directory and see how that works.

Before you have to play sound, you must be familiar with PlaySound() Win32 API function.

private SoundPlayer player = new SoundPlayer();

/// Button click event handler.
private void AsyncBtn_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        // Set .wav file as TextBox.Text.
        textBox1.Text = openFileDialog1.FileName;

        // Add LoadCompleted event handler.
        player.LoadCompleted += new AsyncCompletedEventHandler(LoadCompleted);

        // Set location of the .wav file.
        player.SoundLocation = openFileDialog1.FileName;

        // Load asynchronously.
        player.LoadAsync();
    }
}

/// LoadCompleted event handler.
private void LoadCompleted(object sender, AsyncCompletedEventArgs args)
{
    player.Play();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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