WPF Audio Player using MediaElement sometimes lags - c#

this is the source code for the audio player:
public partial class MainWindow : Window
{
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
mPlayer.LoadedBehavior = MediaState.Manual;
mPlayer.UnloadedBehavior = MediaState.Manual;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(500);
timer.Tick += timer_Tick;
mPlayer.MediaOpened += mPlayer_MediaOpened;
}
void mPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
TimeSpan ts = mPlayer.NaturalDuration.TimeSpan;
SeekSlider.Maximum = ts.TotalSeconds;
}
void timer_Tick(object sender, EventArgs e)
{
SeekSlider.Value = mPlayer.Position.TotalSeconds;
}
private MediaElement mPlayer = new MediaElement();
private void ButtonOpen_Click(object sender, RoutedEventArgs e)
{
try
{
var ofd = new OpenFileDialog();
if (ofd.ShowDialog() == true)
{
timer.Start();
mPlayer.Source = new Uri(ofd.FileName);
mPlayer.Volume = VolumeSlider.Value;
timer.Start();
mPlayer.Play();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void ButtonPlay_Click(object sender, RoutedEventArgs e)
{
mPlayer.Play();
timer.Start();
}
private void ButtonPause_Click(object sender, RoutedEventArgs e)
{
mPlayer.Pause();
timer.Stop();
}
private void ButtonStop_OnClick(object sender, RoutedEventArgs e)
{
timer.Stop();
mPlayer.Stop();
}
private void SeekSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
mPlayer.Position = TimeSpan.FromSeconds(SeekSlider.Value);
}
private void VolumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
mPlayer.Volume = VolumeSlider.Value;
}
}
I don't know why it has sudden lags. Please help me in finding the problem.
If you think that MediaElement is not appropriate for playing different kinds of audio files. Please suggest an alternative.

The SeekSlider_ValueChanged event was firing too often. so that was causing some lag.
So i solved the problem using the Thumb.DragCompleted event. After this the playback is pretty smooth.

Related

How to make a label change its text every some time in C# windows forms

I have a label that I want to update every 5 seconds. It should change from 1921 to 1922 onward till 1992. I have tried using a timer but it gave me an error about being accessed on the wrong thread. The code I used was:
public partial class Form1 : Form
{
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
label1.Text = x.ToString();
x += 1;
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}
}
Try this:
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
//Invoke makes the UI thread call the delegate.
Invoke((MethodInvoker)delegate {label1.Text = x.ToString(); });
x += 1;
}
try this
private readonly object y = new object();
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
Invoke((MethodInvoker)(() => { lock (y) { label1.Text = x.ToString(); x++; } }));
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}

Why is my Web Camera is not streaming a video in c#?

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
VideoCapture capture = new VideoCapture();
var img = capture.QueryFrame();
imageBox1.Image = img;
}
}
}
This is my code and I can't seem to make it work. Everything seems fine, I am unable to Debug. My ImageBox is not streaming a video just showing an image.
I found the answer. Thank You!. Everyone :)
public partial class Form1 : Form
{
bool _streaming;
VideoCapture _capture;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_streaming = false;
_capture = new VideoCapture();
}
private void Button2_Click(object sender, EventArgs e)
{
if (_streaming == false)
{
//Start streaming
Application.Idle += streaming;
button2.Text = "Stop Streaming";
}
else
{
Application.Idle -= streaming;
button2.Text = "Start Streaming";
}
_streaming = !_streaming;
}
private void streaming(object sender, EventArgs e)
{
var img = _capture.QueryFrame();
imageBox2.Image = img;
}
private void Button1_Click(object sender, EventArgs e)
{
imageBox1.Image = imageBox2.Image;
}

Not returning elapsed time in milliseconds

I've built this simple stopwatch program to measure time in the format of: 00:00:000 [minutes:seconds:milliseconds], but the code ignores the format and counts up like this: 00:00:[seconds here][milliseconds here], so as a result I can only get the elapsed time in 10s of milliseconds and not the individual millisecond.
Here's the display:
The actual time elapsed is 3 seconds and 610 milliseconds.
Code:
namespace stopwatch_1
{
public partial class Form1 : Form
{
int timeMinutes, timeSeconds, timeMSeconds;
bool timerActive;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
resetTime();
}
private void buttonStart_Click(object sender, EventArgs e)
{
timerActive = true;
}
private void buttonStop_Click(object sender, EventArgs e)
{
timerActive = false;
}
private void buttonReset_Click(object sender, EventArgs e)
{
resetTime();
}
private void resetTime()
{
timerActive = false;
timeMinutes = 0;
timeSeconds = 0;
timeMSeconds = 0;
}
private void timerStopwatch_Tick(object sender, EventArgs e)
{
if (timerActive == true)
{
timeMSeconds++;
if (timeMSeconds >= 1000)
{
timeMSeconds = 0;
timeSeconds++;
if (timeSeconds >= 60)
{
timeSeconds = 0;
timeMinutes++;
}
}
}
timerDraw();
}
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", timeMinutes);
labelSeconds.Text = String.Format("{0:00}", timeSeconds);
labelMSeconds.Text = String.Format("{0:000}", timeMSeconds);
}
}
}`
The timer interval is set to one, and I've double checked that all variables are pointing to the right labels so I think the problem lies with where I've formatted the string to display, but I'm not sure where I've gone wrong:
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", timeMinutes);
labelSeconds.Text = String.Format("{0:00}", timeSeconds);
labelMSeconds.Text = String.Format("{0:000}", timeMSeconds);
}
I don't really know how to use string.format in this context, so this is probably where I've gone wrong, all help would be appreciated
The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds.
You should use a Stopwatch to get a more accurate resolution:
Stopwatch stopwatch;
public Form1()
{
InitializeComponent();
stopwatch = new Stopwatch();
}
private void Form1_Load(object sender, EventArgs e)
{
// do nothing
}
private void buttonStart_Click(object sender, EventArgs e)
{
stopwatch.Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
stopwatch.Stop();
}
private void buttonReset_Click(object sender, EventArgs e)
{
stopwatch.Reset();
}
private void timerStopwatch_Tick(object sender, EventArgs e)
{
timerDraw();
}
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", stopwatch.Elapsed.Minutes);
labelSeconds.Text = String.Format("{0:00}", stopwatch.Elapsed.Seconds);
labelMSeconds.Text = String.Format("{0:000}", stopwatch.Elapsed.Milliseconds);
}
EDIT:
You should also reduce the Interval on your timer, since there is no need to refresh the labels on a 1ms interval anymore.

combination of MouseDown and timer

I try to load a function like "holdFunction", during touching(MouseDown) and during at max 1 second .
So when user try to touch and hold for a second I have to call the function, and this isn't related to mouseUp.
Maybe I must to combine these:
private DateTime dtHold;
private void EditProduct_MouseDown(object sender, MouseButtonEventArgs e)
{
dtHold = DateTime.Now;
}
private void EditProduct_MouseUp(object sender, MouseButtonEventArgs e)
{
TimeSpan interval = TimeSpan.FromSeconds(1);
if (DateTime.Now.Subtract(dtHold) > interval)
{
//HoldFunction();
}
}
and
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void EditProduct_MouseDown(object sender, MouseButtonEventArgs e)
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0,1,0);
dispatcherTimer.Start();
}
private int _sec = 0;
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
_sec = _sec + 1;
if (_sec == 2)
{
dispatcherTimer.Stop();
{
//HoldFunction();
}
_sec = 0;
return;
}
}
Is this what you are looking for?
If the User holds the MouseDown for 1 second, the evnt is fired?
public partial class Window2 : Window
{
private DispatcherTimer _DispatcherTimer = new DispatcherTimer();
public Window2()
{
InitializeComponent();
MouseDown += _MouseDown;
MouseUp += _MouseUp;
_DispatcherTimer.Interval = TimeSpan.FromSeconds(1.0);
_DispatcherTimer.Tick += _DispatcherTimer_Tick;
}
private void _DispatcherTimer_Tick(object sender, EventArgs e)
{
_DispatcherTimer.Stop();
Title = DateTime.Now.ToString();
}
private void _MouseUp(object sender, MouseButtonEventArgs e)
{
_DispatcherTimer.Stop();
}
private void _MouseDown(object sender, MouseButtonEventArgs e)
{
_DispatcherTimer.Start();
}
}

Want to have a slideshow of images on button click in Windows Phone 7

I have stack of images in a grid and i want to implement a slide show for it.I am using Microsoft VS 2010 Express Edition for Windows phone for implemenitng this.Can someone help ? The code is :
using System;
using System.Collections.Generic;
using System.Windows.Threading;
namespace swipe
{
public partial class MainPage : PhoneApplicationPage
{
// private DispatcherTimer tmr = new DispatcherTimer();
private List<string> images = new List<string>();
private int imageIndex = 0;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// tmr.Interval = TimeSpan.FromSeconds(5);
// tmr.Tick += new EventHandler(tmr_Tick);
LoadImages();
ShowNextImage();
}
private void LoadImages()
{
images.Add("/images/Hydrangeas.jpg");
images.Add("/images/Jellyfish.jpg");
images.Add("/images/Koala.jpg");
images.Add("/images/Tulips.jpg");
}
private void ShowNextImage()
{
// String bi = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
myImg.Source = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
imageIndex = (imageIndex + 1) % images.Count;
}
//void tmr_Tick(object sender, EventArgs e)
//{
// ShowNextImage();
//}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//if (!tmr.IsEnabled)
//{
// tmr.Start();
//}
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
//tmr.Stop();
base.OnNavigatedFrom(e);
}
private void Play_Click(object sender, RoutedEventArgs e)
{
ShowNextImage();
}
}
}
Here's a quick example of one way of doing this. It doesn't use a grid of images but I'm sure you can adjust this as you need to.
Edit: reread the title. If you want this to advance on button click get rid of the timer and call ShowNextImage() in the click event.
The page includes the following XAML:
<Image x:Name="myImg" />
The code behind looks like:
private DispatcherTimer tmr = new DispatcherTimer();
private List<string> images = new List<string>();
private int imageIndex = 0;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick += new EventHandler(tmr_Tick);
LoadImages();
ShowNextImage();
}
private void LoadImages()
{
// list the files (includede in the XAP file) here
images.Add("/images/filename1.jpg");
images.Add("/images/filename2.jpg");
images.Add("/images/filename3.jpg");
images.Add("/images/filename4.jpg");
}
private void ShowNextImage()
{
var bi = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
myImg.Source = bi;
imageIndex = (imageIndex + 1) % images.Count;
}
void tmr_Tick(object sender, EventArgs e)
{
ShowNextImage();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (!tmr.IsEnabled)
{
tmr.Start();
}
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
tmr.Stop();
base.OnNavigatedFrom(e);
}
Sample code which shows using a button to advance code can be downloaded from http://cid-cc22250598bf7f04.office.live.com/self.aspx/Public/SlideShowDemo.zip
The easy way is to create a collection of images, and and go to next image in the collection when you go to next page in a pivot page.
A other solution is to create a usercontrol.
Here is a guide how to do it in silverlight ( but not in WP7, but it is very similar ).

Categories

Resources