0

I am trying to make multiple audio files playing simultaneously, so I decide to use thread to trigger them (otherwise the one can only start playing until the previous finished).

This is how I do it.

sounds is a list of SoundPlayers

for (int i = 0; i < sometimes; i++)
{
    SoundPlayer sp = sounds[i];
    Thread thread = new Thread(() =>
    {
        sp.PlayLooping();
    });
    threads.Add(thread);
 }
 foreach (Thread thread in threads)
 {
     thread.Start();
 } 

Then I use a timer to stop all the audio file after 1 second.

foreach(Thread t in threads)
{
    kill_thread(t);
    MessageBox.Show(t.IsAlive.ToString());
}
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void kill_thread(Thread t)
{
   t.Abort();
}

I get kill_thread method from here. With the message pops up from messagebox, the target thread has already been killed in this way. However, the music is keep playing.

Is there any way to stop the music? Thanks in advance!

BWA
  • 5,672
  • 7
  • 34
  • 45
Jieke Wei
  • 173
  • 2
  • 13

2 Answers2

1

You shouldn't be killing any thread, yours or otherwise. In fact, you shouldn't even be creating threads. As the others have said, if you must end a thread, end it gracefully, don't nuke it via Abort. It can leave your process in an unknown state.

Just call:

soundPlayer.Stop();

MSDN:

SoundPlayer.PlayLooping Method

The .wav will be played until the Stop method is called. https://msdn.microsoft.com/en-US/library/system.media.soundplayer.playlooping(v=vs.110).aspx

As for concurrent playback, SoundPlayer isn't designed for elaborate concurrent playback (in fact it won't even do it). You need to use a different media API for that.

See also

  • Microsoft DirectShow (been around since the '90s; rock solid; part of Media Server and Media Center; COM API; though not managed, COM is pretty easy to call from .NET)

  • Media Foundation (new kid on the block; no managed API either)

Community
  • 1
  • 1
  • read my description of the question. Creating the thread is to play multiple music simultaneously, not about "playing a music" – Jieke Wei Feb 07 '18 at 14:22
  • @JiekeWei Also your title explicitly says _"**stop** music playing in a thread"_ and your body _"Is there any way to **stop** the music?"_ which I have covered, not _"play multiple music simultaneously"_. `SoundPlayer` isn't designed for elaborate concurrent playback. You need to use a different media API for that. Feel free to ask a _new question_ –  Feb 07 '18 at 14:39
  • Yeah, I found that problem. I cannot hear the audio files playing in the same time, only the last one. I will consider about a new api – Jieke Wei Feb 07 '18 at 14:44
0

This is because the PlayLooping() method starts a new thread itself, so killing your thread does not stop the player thread.

https://msdn.microsoft.com/it-it/library/system.media.soundplayer.playlooping(v=vs.110).aspx