📜  c# soundplayer playlooping - C# (1)

📅  最后修改于: 2023-12-03 14:39:44.046000             🧑  作者: Mango

C# SoundPlayer PlayLooping

The SoundPlayer class in C# allows playing sounds in Windows Forms applications. One useful feature of SoundPlayer is the ability to play a sound in a loop using the PlayLooping method.

Introduction

The SoundPlayer class is part of the System.Media namespace in C#, which provides a simple way to play WAV files synchronously. The PlayLooping method allows you to continuously play a sound until it is explicitly stopped.

Usage

To use the PlayLooping method, follow these steps:

  1. Import the System.Media namespace:

    using System.Media;
    
  2. Create an instance of the SoundPlayer class:

    SoundPlayer player = new SoundPlayer();
    
  3. Set the sound file path using the SoundLocation property:

    player.SoundLocation = "path/to/sound.wav";
    
  4. Call the PlayLooping method to start playing the sound in a loop:

    player.PlayLooping();
    
  5. Stop the sound by calling the Stop method:

    player.Stop();
    
Example

Here is an example that demonstrates the usage of PlayLooping:

using System;
using System.Media;

namespace SoundPlayerExample
{
    class Program
    {
        static void Main(string[] args)
        {
            SoundPlayer player = new SoundPlayer();
            player.SoundLocation = "path/to/sound.wav";
            
            // Start playing the sound in a loop
            player.PlayLooping();
            
            Console.WriteLine("Press any key to stop playing.");
            Console.ReadKey();
            
            // Stop playing the sound
            player.Stop();
        }
    }
}
Notes
  • The SoundPlayer class supports only WAV files.
  • It is important to handle exceptions that may occur while using SoundPlayer. For example, if the file path is invalid or the file is not a WAV file, an exception will be thrown.
  • Make sure to release system resources by calling the Dispose method of the SoundPlayer class when you are done using it.

For more information about the SoundPlayer class, you can refer to the Microsoft documentation.

Note: The code snippets provided in this answer are written in C# and formatted using markdown syntax.