Question

in my form, I have a small media player, it's pretty basic, it has the basic functionalists nest, previous, play, stop, volume increasing and a track bar. I was able to seek the song by dragging the track bar via this code:: (Assuming that the maximum value of the track bar is the total number of seconds of the sound file)

private void SeekBar_Scroll(object sender, EventArgs e)
{
   Player.Position = TimeSpan.FromSeconds(SeekBar.Value);
} 

But I wasn't able to make the bar move forward by itself when the music is playing .. I came up with this idea:

let's say we have a 90 secs duration song. now the track bar maximum value is 100 so: 100 --> 90 1 --> X X = 0.9 sec this is the interval between the ticks of the bar and the value that the track bar value should be increased in every tick. Here is my code:

while (SeekBar.Value < 100)
{
  System.Windows.Duration duration = Player.NaturalDuration;
  SeekBar.Value += duration.TimeSpan.Seconds / 100;
  Thread.Sleep(duration.TimeSpan.Seconds * 10);
}

Now I think this should be run in a separate thread right ? but the problem, when i do that, I get the annoying message of saying that the TrackBar is being used in a thread other than the thread it was created on .. how can i get around that ?

I wanted to put this code in both the MouseLeave and MouseEnter events, but it's pointless, cuz it will be on the same thread and the app will freeze..

How can i make the bar move by it self ?

Was it helpful?

Solution

You should create a WinForms Timer with an interval or 1,000 milliseconds, and update the trackbar in its Tick event.

OTHER TIPS

It sounds like you have the hardest part done (mapping the length of the scroll bar to the length of the audio file). The rest is easy.

You can tackle this with a Timer. Set the interval to some value (such as 1000ms or maybe 500ms, and in Tick, update the scrollbar (call SeekBar_Scroll). For the exact interval, test and see what looks the most natural.

A while-loop will probably eat unnecessary CPU, not to mention lock up the rest of your application.

To get around the control updating, you need to check this SO question. You need to check control.InvokeRequired and set it via the Invoke method if that's the case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top