Reputation: 21
What I am trying to do is play a sound file for an item selected in a list box. For example: item 1 plays "1.mp3" and item 2 plays "2.mp3" BUT the thing is, it needs to stop the other audio and then play. It does this when playing wavs:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
SoundPlayer player = new SoundPlayer();
player.SoundLocation = "S1.mp3";
player.Play();
}
if (listBox1.SelectedIndex == 1)
{
SoundPlayer player = new SoundPlayer();
player.SoundLocation = "S2.mp3";
player.Play();
}
if (listBox1.SelectedIndex == 2)
{
SoundPlayer player = new SoundPlayer();
player.SoundLocation = "S3.mp3";
player.Play();
}
}
But wavs are too big so I need an alternative.
I have looked all over to find a solution but nothing works :( NAudio plays the sounds on top of each other and I couldn't find out how to use NVorbis and oggsharp etc.
Using any format of audio is fine, I don't care. I just can't use wav.
Upvotes: 1
Views: 7239
Reputation: 10744
Have one instance of SoundPlayer
and before you play the next audio, stop the current one.
public class Sounds
{
SoundPlayer player = new SoundPlayer();
public void Play(string file)
{
player.Stop();
player.SoundLocation = file;
player.Play();
}
}
For MP3 you can use WMPLib.WindowsMediaPlayer
To create the Windows Media Player control programmatically, you must first add a reference to wmp.dll, which is found in the \Windows\system32 folder.
public class Sounds
{
WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
private void PlayFile(String url)
{
player.URL = url;
player.controls.play();
}
}
Usage:
public class MyThing
{
Sounds sounds = new Sounds();
string SelectedFile;
public void OnPlayClick()
{
sounds.PlayFile(SelectedFile);
}
}
Upvotes: 3