📅  最后修改于: 2023-12-03 14:39:44.046000             🧑  作者: Mango
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.
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.
To use the PlayLooping
method, follow these steps:
Import the System.Media
namespace:
using System.Media;
Create an instance of the SoundPlayer
class:
SoundPlayer player = new SoundPlayer();
Set the sound file path using the SoundLocation
property:
player.SoundLocation = "path/to/sound.wav";
Call the PlayLooping
method to start playing the sound in a loop:
player.PlayLooping();
Stop the sound by calling the Stop
method:
player.Stop();
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();
}
}
}
SoundPlayer
class supports only WAV files.SoundPlayer
. For example, if the file path is invalid or the file is not a WAV file, an exception will be thrown.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.