问题
I have linked the import button with a media element so i can get the song to play.
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".txt";
dlg.Filter = "WAV Files (*.wav)|*.wav|MP3 Files (*.mp3)|*.mp3|MP4 Files (*.mp4)|*.mp4|WMA Files (*.wma)|*.wma|SWA (*.swa)|*.swa";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
meMedia1.Source = new Uri(dlg.FileName);
meMedia1.Play();
//txtFileLocation.Text = filename;
Now, the sound plays but what I want to do is link a slider so they can skip some of the song and also a label above the slider so that it read how long into the song it is. This is how my application looks now to give you an idea.
http://i.stack.imgur.com/sVtrd.png
Thank You.
EDIT : Got the seek to change the song position but I still cant get it manually moving to the time of the song, for example if I skip to the middle of the song, and let the song finish my slider will still be in the middle and I want it to be at the end.
回答1:
One approach is to create a DispatcherTimer that ticks every 200-800ms (depending on your preference for update speed) that syncs the slider to the player's current Position. That code might look similar to this:
// In the class members area
private DispatcherTimer _timer = null;
// In your constructor/loaded method
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(500);
_timer.Tick += _timer_tick;
// Timer's tick method
void _timer_tick(object sender, EventArgs e)
{
// Convert duration to an integer percentage based on current position of
// playback and update the slider control
TimeSpan ts = meMedia1.NaturalDuration.TimeSpan;
int percent = int( meMedia1.Position / ts.Seconds * 100 );
mySliderControl.Value = percent;
}
Note that this assumes you have a Slider
whose Min is 0 and Max is 100. You can bump it up to 0-1000 (and change the math accordingly) to get finer granularity. This also doesn't allow the slider to push user interaction back to the player, but gives you an idea of one way to get the opposite. You can add an event handler to the Slider such that when the user begins interacting, this _timer
is stopped ( _timer.Stop()
) so updates to the media position stop updating the slider and instead start doing your slider -> media position updates instead. Then when the user lets go of the slider, turn the _timer
back on ( _timer.Start()
).
来源:https://stackoverflow.com/questions/20212853/link-media-element-on-wpf-with-label-and-slider