private SoundPlayer player; private void btnStop_Click(object sender, EventArgs e) { if (player != null) { player.Stop(); } } private void btnPlay_Click(object sender, EventArgs e) { player = new SoundPlayer("C:\\Windows\\Media\\chimes.wav"); player.Play(); }
private SoundPlayer bgMusic; private bool gameEnded = false; private void PlayBackgroundMusic() { bgMusic = new SoundPlayer(Properties.Resources.background_music); bgMusic.PlayLooping(); } private void GameOver() { gameEnded = true; bgMusic.Stop(); }In this example, we have a game with background music. The `PlayBackgroundMusic()` method initializes the `SoundPlayer` object with the background music and starts playing it in a loop using the `PlayLooping()` method. When the game is over, the `GameOver()` method is called which sets the `gameEnded` flag to true and stops the background music using the `Stop()` method. Package Library: System.Media