how to set capture source of AudioVideoCaptureDevice on Windows Phone - c#

I'm trying to capture video on Windows Phone using the AudioVideoCaptureDevice but when I try to set the captureSource I get a error message saying " Operation not valid due to the state of the object". Can you tell me what to do right in the following code?
Code snippet:
// Viewfinder for capturing video.
private VideoBrush videoRecorderBrush;
// Source and device for capturing video.
private CaptureSource _cs;
private VideoCaptureDevice _cd;
private AudioVideoCaptureDevice vcDevice;
double w, h;
// File details for storing the recording.
private IsolatedStorageFileStream isoVideoFile;
private FileSink fileSink;
private string isoVideoFileName = "iClips_Video.mp4";
private StorageFile sfVideoFile;
// For managing button and application state.
private enum ButtonState { Initialized, Stopped, Ready, Recording, Playback, Paused, NoChange, CameraNotSupported };
private ButtonState currentAppState;
// Constructor
public MainPage()
{
try
{
InitializeComponent();
//setup recording
// Prepare ApplicationBar and buttons.
PhoneAppBar = (ApplicationBar)ApplicationBar;
PhoneAppBar.IsVisible = true;
StartRecording = ((ApplicationBarIconButton)ApplicationBar.Buttons[0]);
StopPlaybackRecording = ((ApplicationBarIconButton)ApplicationBar.Buttons[1]);
StartPlayback = ((ApplicationBarIconButton)ApplicationBar.Buttons[2]);
PausePlayback = ((ApplicationBarIconButton)ApplicationBar.Buttons[3]);
SetScreenResolution();
//initialize the camera task
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
if (isFilePresent("username") && isFilePresent("Password"))
{
if (isFilePresent("IsProfilePhotoOnServer"))
{
connectToSocket();
}
else
{
SignUpProfilePhoto();
}
}
else
{
SignIn();
}
}
catch (Exception ex)
{
this.Dispatcher.BeginInvoke(delegate()
{
MessageBox.Show("Constructor Error:\n"+ ex.Message);
});
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// Initialize the video recorder.
InitializeVideoRecorder();
//prepare shutter hot keys
CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;
CameraButtons.ShutterKeyPressed += OnButtonFullPress;
CameraButtons.ShutterKeyReleased += OnButtonRelease;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
// Dispose of camera and media objects.
DisposeVideoPlayer();
DisposeVideoRecorder();
base.OnNavigatedFrom(e);
CameraButtons.ShutterKeyHalfPressed -= OnButtonHalfPress;
CameraButtons.ShutterKeyPressed -= OnButtonFullPress;
CameraButtons.ShutterKeyReleased -= OnButtonRelease;
}
protected override void OnOrientationChanged(OrientationChangedEventArgs e)
{
if (vcDevice != null)
{
if (e.Orientation == PageOrientation.LandscapeLeft)
{
txtDebug.Text = "LandscapeLeft";
videoRecorderBrush.RelativeTransform =
new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
//rotate logo
if (logo != null)
{
RotateTransform rt = new RotateTransform();
rt.Angle = 90;
//default rotation is around top left corner of the control,
//but you sometimes want to rotate around the center of the control
//to do that, you need to set the RenderTransFormOrigin
//of the item you're going to rotate
//I did not test this approach, maybe You're going to need to use actual coordinates
//so this bit is for information purposes only
logo.RenderTransformOrigin = new Point(0.5, 0.5);
logo.RenderTransform = rt;
}
//rotate sign in link
if (MyGrid != null)
{
RotateTransform rt = new RotateTransform();
rt.Angle = 90;
//default rotation is around top left corner of the control,
//but you sometimes want to rotate around the center of the control
//to do that, you need to set the RenderTransFormOrigin
//of the item you're going to rotate
//I did not test this approach, maybe You're going to need to use actual coordinates
//so this bit is for information purposes only
MyGrid.RenderTransformOrigin = new Point(0.5, 0.5);
MyGrid.RenderTransform = rt;
}
}
if (e.Orientation == PageOrientation.PortraitUp)
{
txtDebug.Text = "PortraitUp";
videoRecorderBrush.RelativeTransform =
new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
//rotate logo
if (logo != null)
{
RotateTransform rt = new RotateTransform();
rt.Angle = 0;
//default rotation is around top left corner of the control,
//but you sometimes want to rotate around the center of the control
//to do that, you need to set the RenderTransFormOrigin
//of the item you're going to rotate
//I did not test this approach, maybe You're going to need to use actual coordinates
//so this bit is for information purposes only
logo.RenderTransformOrigin = new Point(0.5, 0.5);
logo.RenderTransform = rt;
}
//rotate sign in link
if (MyGrid != null)
{
RotateTransform rt = new RotateTransform();
rt.Angle = 0;
//default rotation is around top left corner of the control,
//but you sometimes want to rotate around the center of the control
//to do that, you need to set the RenderTransFormOrigin
//of the item you're going to rotate
//I did not test this approach, maybe You're going to need to use actual coordinates
//so this bit is for information purposes only
MyGrid.RenderTransformOrigin = new Point(0.5, 0.5);
MyGrid.RenderTransform = rt;
}
}
if (e.Orientation == PageOrientation.LandscapeRight)
{
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "LandscapeRight";
// Rotate for LandscapeRight orientation.
//videoRecorderBrush.RelativeTransform =
//new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 180 };
//rotate logo
if (logo != null)
{
RotateTransform rt = new RotateTransform();
rt.Angle = -90;
//default rotation is around top left corner of the control,
//but you sometimes want to rotate around the center of the control
//to do that, you need to set the RenderTransFormOrigin
//of the item you're going to rotate
//I did not test this approach, maybe You're going to need to use actual coordinates
//so this bit is for information purposes only
logo.RenderTransformOrigin = new Point(0.5, 0.5);
logo.RenderTransform = rt;
}
//rotate MyGrid
if (MyGrid != null)
{
RotateTransform rt = new RotateTransform();
rt.Angle = -90;
//default rotation is around top left corner of the control,
//but you sometimes want to rotate around the center of the control
//to do that, you need to set the RenderTransFormOrigin
//of the item you're going to rotate
//I did not test this approach, maybe You're going to need to use actual coordinates
//so this bit is for information purposes only
MyGrid.RenderTransformOrigin = new Point(0.5, 0.5);
MyGrid.RenderTransform = rt;
}
});
}
if (e.Orientation == PageOrientation.PortraitDown)
{
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "PortraitDown";
videoRecorderBrush.RelativeTransform =
new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 270 };
});
}
}
}
// Hardware shutter button Hot-Actions.
private void OnButtonHalfPress(object sender, EventArgs e)
{
//toggle between video- play and pause
try
{
this.Dispatcher.BeginInvoke(delegate()
{
if (StartPlayback.IsEnabled)
{
PlayVideo();
}
if (PausePlayback.IsEnabled)
{
PauseVideo();
}
});
}
catch (Exception focusError)
{
// Cannot focus when a capture is in progress.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = focusError.Message;
});
}
}
private void OnButtonFullPress(object sender, EventArgs e)
{
// Focus when a capture is not in progress.
try
{
this.Dispatcher.BeginInvoke(delegate()
{
if (vcDevice != null)
{
//stopVideoPlayer if it's playing back
if (currentAppState == ButtonState.Playback || currentAppState == ButtonState.Paused)
{
DisposeVideoPlayer();
StartVideoPreview();
}
if (StartRecording.IsEnabled)
{
StartVideoRecording();
}
else
{
StopVideoRecording();
}
}
});
}
catch (Exception focusError)
{
// Cannot focus when a capture is in progress.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = focusError.Message;
});
}
}
private void OnButtonRelease(object sender, EventArgs e)
{
try
{
this.Dispatcher.BeginInvoke(delegate()
{
});
}
catch (Exception focusError)
{
// Cannot focus when a capture is in progress.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = focusError.Message;
});
}
}
// Update the buttons and text on the UI thread based on app state.
private void UpdateUI(ButtonState currentButtonState, string statusMessage)
{
// Run code on the UI thread.
Dispatcher.BeginInvoke(delegate
{
switch (currentButtonState)
{
// When the camera is not supported by the phone.
case ButtonState.CameraNotSupported:
StartRecording.IsEnabled = false;
StopPlaybackRecording.IsEnabled = false;
StartPlayback.IsEnabled = false;
PausePlayback.IsEnabled = false;
break;
// First launch of the application, so no video is available.
case ButtonState.Initialized:
StartRecording.IsEnabled = true;
StopPlaybackRecording.IsEnabled = false;
StartPlayback.IsEnabled = false;
PausePlayback.IsEnabled = false;
break;
// Ready to record, so video is available for viewing.
case ButtonState.Ready:
StartRecording.IsEnabled = true;
StopPlaybackRecording.IsEnabled = false;
StartPlayback.IsEnabled = true;
PausePlayback.IsEnabled = false;
break;
// Video recording is in progress.
case ButtonState.Recording:
StartRecording.IsEnabled = false;
StopPlaybackRecording.IsEnabled = true;
StartPlayback.IsEnabled = false;
PausePlayback.IsEnabled = false;
break;
// Video playback is in progress.
case ButtonState.Playback:
StartRecording.IsEnabled = false;
StopPlaybackRecording.IsEnabled = true;
StartPlayback.IsEnabled = false;
PausePlayback.IsEnabled = true;
break;
// Video playback has been paused.
case ButtonState.Paused:
StartRecording.IsEnabled = false;
StopPlaybackRecording.IsEnabled = true;
StartPlayback.IsEnabled = true;
PausePlayback.IsEnabled = false;
break;
default:
break;
}
// Display a message.
txtDebug.Text = statusMessage;
// Note the current application state.
currentAppState = currentButtonState;
});
}
public async void InitializeVideoRecorder()
{
try
{
if (_cs == null)
{
_cs = new CaptureSource();
fileSink = new FileSink();
_cd = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
CameraSensorLocation location = CameraSensorLocation.Back;
var captureResolutions =
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(location);
vcDevice = await AudioVideoCaptureDevice.OpenAsync(location, captureResolutions[0]);
vcDevice.RecordingFailed += OnCaptureFailed;
vcDevice.VideoEncodingFormat = CameraCaptureVideoFormat.H264;
vcDevice.AudioEncodingFormat = CameraCaptureAudioFormat.Aac;
// Initialize the camera if it exists on the phone.
if (vcDevice != null)
{
//initialize fileSink
await InitializeFileSink();
// Create the VideoBrush for the viewfinder.
videoRecorderBrush = new VideoBrush();
videoRecorderBrush.SetSource(_cs);
// Display the viewfinder image on the rectangle.
viewfinderRectangle.Fill = videoRecorderBrush;
_cs.Start();
// Set the button state and the message.
UpdateUI(ButtonState.Initialized, "Tap record to start recording...");
}
else
{
// Disable buttons when the camera is not supported by the phone.
UpdateUI(ButtonState.CameraNotSupported, "A camera is not supported on this phone.");
}
}
}
catch(Exception ex)
{
MessageBox.Show("InitializeVideoRecorder Error:\n" + ex.Message);
}
}
public async Task InitializeFileSink()
{
StorageFolder isoStore = ApplicationData.Current.LocalFolder;
sfVideoFile = await isoStore.CreateFileAsync(
isoVideoFileName,
CreationCollisionOption.ReplaceExisting);
}
private void OnCaptureFailed(AudioVideoCaptureDevice sender, CaptureFailedEventArgs args)
{
MessageBox.Show(args.ToString());
}
private void OnCaptureSourceFailed(object sender, ExceptionRoutedEventArgs e)
{
MessageBox.Show(e.ErrorException.Message.ToString());
}
// Set the recording state: display the video on the viewfinder.
private void StartVideoPreview()
{
try
{
// Display the video on the viewfinder.
if (_cs.VideoCaptureDevice != null
&& _cs.State == CaptureState.Stopped)
{
// Add captureSource to videoBrush.
videoRecorderBrush.SetSource(_cs);
// Add videoBrush to the visual tree.
viewfinderRectangle.Fill = videoRecorderBrush;
_cs.Start();
// Set the button states and the message.
UpdateUI(ButtonState.Ready, "Ready to record.");
//Create optional Resolutions
}
}
// If preview fails, display an error.
catch (Exception e)
{
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "ERROR: " + e.Message.ToString();
});
}
}
// Set recording state: start recording.
private void StartVideoRecording()
{
try
{
// Connect fileSink to captureSource.
if (_cs.VideoCaptureDevice != null
&& _cs.State == CaptureState.Started)
{
_cs.Stop();
// Connect the input and output of fileSink.
fileSink.CaptureSource = _cs;
fileSink.IsolatedStorageFileName = isoVideoFileName;
}
// Begin recording.
if (_cs.VideoCaptureDevice != null
&& _cs.State == CaptureState.Stopped)
{
_cs.Start();
}
// Set the button states and the message.
UpdateUI(ButtonState.Recording, "Recording...");
StartTimer();
}
// If recording fails, display an error.
catch (Exception e)
{
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "ERROR: " + e.Message.ToString();
});
}
}
// Set the recording state: stop recording.
private void StopVideoRecording()
{
try
{
// Stop recording.
if (_cs.VideoCaptureDevice != null
&& _cs.State == CaptureState.Started)
{
_cs.Stop();
// Disconnect fileSink.
fileSink.CaptureSource = null;
fileSink.IsolatedStorageFileName = null;
// Set the button states and the message.
UpdateUI(ButtonState.Stopped, "Preparing viewfinder...");
StopTimer();
StartVideoPreview();
}
}
// If stop fails, display an error.
catch (Exception e)
{
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "ERROR: " + e.Message.ToString();
});
}
}
// Start the video recording.
private void StartRecording_Click(object sender, EventArgs e)
{
// Avoid duplicate taps.
StartRecording.IsEnabled = false;
StartVideoRecording();
}
private void DisposeVideoRecorder()
{
if (_cs != null)
{
// Stop captureSource if it is running.
if (_cs.VideoCaptureDevice != null
&& _cs.State == CaptureState.Started)
{
_cs.Stop();
}
// Remove the event handler for captureSource.
_cs.CaptureFailed -= OnCaptureFailed;
// Remove the video recording objects.
_cs = null;
vcDevice = null;
fileSink = null;
videoRecorderBrush = null;
}
}
private void OnCaptureFailed(object sender, ExceptionRoutedEventArgs e)
{
throw new NotImplementedException();
}
//STOP WATCH
private void StartTimer()
{
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
startTime = System.DateTime.Now;
}
private void StopTimer()
{
dispatcherTimer.Stop();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
System.DateTime now = System.DateTime.Now;
txtRecTime.Text = now.Subtract(startTime).ToString();
}
the error is thrown inside initializeVideoRecorder().

Seems like you're code is too long to analyze as #john mentioned in the comment. But since you've suggested to post some helpful links here you go: Following these steps here in msdn, would work without any issues as I've tried it once.
If you really need a sample to kick off, there's one from msdn. Hope you'll maximize the utilities.

I figured out I have to pass the capture device to the videobrush to make it work. I'm still not sure where and if I should use CaptureSource when capturing with AudioVideoCaptureDevice. Anyway here is the solution code:
// Create the VideoBrush for the viewfinder.
videoRecorderBrush = new VideoBrush();
videoRecorderBrush.SetSource(vcDevice); //substitute vcDevice with captureSource - vcDevice is the reference of AudioVideoCaptureDevice
// Display the viewfinder image on the rectangle.
viewfinderRectangle.Fill = videoRecorderBrush;

Related

Cannot get Thread and animation Rotation to work

This is my control:
I am getting this to rotate, with this code:
Global variable, bool IsTriangleAnimRunning = false;
And the rest of the code:
public void AnimateTriangle()
{
var rotation = (int)((100 / 100d) * 45 * 1); // Max 45 degree rotation
var duration = (int)(750 * (100 / 100d)); // Max 750ms rotation
while (IsTriangleAnimRunning != false)
{
MyTriangle.Dispatcher.BeginInvoke(
(Action)(() =>
{
var anim = new DoubleAnimation
{
To = rotation,
Duration = new Duration(TimeSpan.FromMilliseconds(duration)),
AutoReverse = true
};
var rt = new RotateTransform();
MyTriangle.RenderTransform = rt;
rt.BeginAnimation(RotateTransform.AngleProperty, anim);
}), DispatcherPriority.ContextIdle);
Thread.Sleep(duration * 2);
}
}
The event handler for the button, that triggers the animation:
public void HandleTriangleEvents(object sender, RoutedEventArgs a)
{
Thread t_triagle = new Thread(new ThreadStart(this.AnimateTriangle));
Button btn = (Button)sender;
if (btn.Name == "btnStartTriangleAnim")
{
IsTriangleAnimRunning = true;
btnStartTriangleAnim.IsEnabled = false;
t_triagle.Start();
}
else
{
IsTriangleAnimRunning = false;
btnStartTriangleAnim.IsEnabled = true;
t_triagle.Abort();
}
}
It behaves in an unatural way, because, when I stop it, it resets to its regular position. I am assuming it, does this for some reason, that I cannot understand. Also, for some reason, this code does not get it to run constantly, but only once.
Desired functionality:
If, I hit start button, run the thread and keep on rotating, while thread is running. If, I hit, stop, then stop in the current state of rotation. If I hit start, run the thread again and keep rotating back and forth.
--
Tested with Task Async, runs slower and doesn't repeat.
private async Task AnimateTriangle()
{
double rotation = 45d;
double duration = 100d;
var anim = new DoubleAnimation
{
To = rotation,
Duration = TimeSpan.FromMilliseconds(duration),
AutoReverse = true,
RepeatBehavior = RepeatBehavior.Forever
};
var transform = MyTriangle.RenderTransform as RotateTransform;
await Task.Factory.StartNew(() =>
{
while (IsTriangleAnimRunning != false)
{
MyTriangle.Dispatcher.Invoke(() =>
{
if (transform == null)
{
transform = new RotateTransform();
MyTriangle.RenderTransform = transform;
}
transform.BeginAnimation(RotateTransform.AngleProperty, anim);
}, DispatcherPriority.ContextIdle);
if (IsTriangleAnimRunning == false)
{
MyTriangle.Dispatcher.Invoke(() =>
{
if (MyTriangle.RenderTransform is RotateTransform)
{
var angle = transform.Angle; // current animated value
transform.Angle = angle;
transform.BeginAnimation(RotateTransform.AngleProperty, null);
}
}, DispatcherPriority.ContextIdle);
}
}
});
}
You do not need to start a thread.
Start an animation that runs forever, until you reset it by setting a null animation.
Before you reset it, explicitly set the value of the target property to the current animated value.
Reuse the existing RotateTransform instead of re-assigning one each time you start the animation.
private void StartButtonClick(object sender, RoutedEventArgs e)
{
double rotation = 45d;
double duration = 750d;
var anim = new DoubleAnimation
{
To = rotation,
Duration = TimeSpan.FromMilliseconds(duration),
AutoReverse = true,
RepeatBehavior = RepeatBehavior.Forever
};
var transform = MyTriangle.RenderTransform as RotateTransform;
if (transform == null)
{
transform = new RotateTransform();
MyTriangle.RenderTransform = transform;
}
transform.Angle = 0d;
transform.BeginAnimation(RotateTransform.AngleProperty, anim);
}
private void StopButtonClick(object sender, RoutedEventArgs e)
{
if (MyTriangle.RenderTransform is RotateTransform transform)
{
var angle = transform.Angle; // current animated value
transform.Angle = angle;
transform.BeginAnimation(RotateTransform.AngleProperty, null);
}
}

How do I make a timer that changes how many ticks he runs on different occasions?

I'm trying to code a Simon Says game and I ran into a problem. I cannot figure out how to make my Randomizer timer (that randomizes which boxes are lit up) to run by waves. I want it to run once, then when it's referred to again - run twice and so on.
This is RandomPlace():
private PictureBox RandomPlace()
{
PictureBox p = new PictureBox();
Random rnd = new Random();
switch (rnd.Next(1, 5))
{
case 1:
p = TopRight;
break;
case 2:
p = TopLeft;
break;
case 3:
p = BottomRight;
break;
case 4:
p = BottomLeft;
break;
}
return p;
} //Gets a random PictureBox
This is RandomImage():
private void RandomImage()
{
TopLeft.Enabled = false;
TopRight.Enabled = false;
BottomLeft.Enabled = false;
BottomRight.Enabled = false;
PictureBox a = RandomPlace();
if (a == TopLeft)
{
TopLeft.Image = Resources.TopLeftLit;
label1.Text = "TopLeft";
Thread.Sleep(500);
TopLeft.Image = Resources.TopLeft;
label2.Text = "TopLeftAFTERSLEEP";
Thread.Sleep(500);
pattern[patternRightNow] = 1;
patternRightNow++;
}
if (a == TopRight)
{
TopRight.Image = Resources.TopRightLit;
label1.Text = "TopRight";
Thread.Sleep(500);
TopRight.Image = Resources.TopRight;
label2.Text = "TopRightAFTERSLEEP"; //FIGURE OUT HOW TO RESET PICTURE
Thread.Sleep(500);
pattern[patternRightNow] = 2;
patternRightNow++;
}
if (a == BottomLeft)
{
this.BottomLeft.Image = Resources.BottomLeftLit;
label1.Text = "BottomLeft";
Thread.Sleep(500);
this.BottomLeft.Image = Resources.BottomLeft;
label2.Text = "BottomLeftAFTERSLEEP";
Thread.Sleep(500);
pattern[patternRightNow] = 3;
patternRightNow++;
}
if (a == BottomRight)
{
this.BottomRight.Image = Resources.BottomRightLit;
label1.Text = "BottomRight";
Thread.Sleep(500);
this.BottomRight.Image = Resources.BottomRight;
label2.Text = "BottomRightAFTERSLEEP";
Thread.Sleep(500);
pattern[patternRightNow] = 4;
patternRightNow++;
}
} //Lits up the random PictureBoxes and sets them back to normal
This is Randomizer_Tick():
rivate void Randomizer_Tick(object sender, EventArgs e)
{
RandomImage();
patternRightNow = 0;
tickCount++;
Randomizer.Stop();
ClickCheck();
} //Use RandomImage() to lit up random PictureBoxes on 5 waves, wave 1 - 1 PictureBox, wave 2 - 2 PictureBoxes and so on.
This is ClickCheck():
private void ClickCheck()
{
TopLeft.Enabled = true;
TopRight.Enabled = true;
BottomLeft.Enabled = true;
BottomRight.Enabled = true;
if (tickCount == clickCount)
{
CheckIfWin();
Randomizer.Start();
}
} //Enables the PictureBoxes to be pressed, after the user input reaches the current wave's amount of PictureBoxes lit up, disable PictureBoxes again and start the randomizer
Instead of using timers, I advise you to look at Tasks. It's much easier to create such statemachines.
Fill a list with colors and play it. Wait until the user pressed enough buttons and check the results.
For example: (haven't tested it, it's just for example/pseudo code)
It might contain some typo's.
private List<int> _sequence = new List<int>();
private List<int> _userInput = new List<int>();
private Random _rnd = new Random(DataTime.UtcNow.Milliseconds);
private bool _running = true;
private bool _inputEnabled = false;
private TaskCompletionSource<object> _userInputReady;
public async void ButtonStart_Click(object sender, EventArgs e)
{
if(_running)
return;
while(_running)
{
// add a color/button
_sequence.Add(_rnd.Next(4));
// play the sequence
for(int color in _sequence)
{
// light-up your image, whatever
Console.WriteLine(color);
// wait here...
await Task.Delay(300);
// turn-off your image, whatever
}
// clear userinput
_userInput.Clear();
_userInputReady = new TaskCompletionSource<object>();
_inputEnabled = true;
// wait for user input.
await _userInputReady.Task;
// compare the user input to the sequence.
for(int i=0;i<_sequence.Count;i++)
{
if(_sequence[i] != _userInput[i])
{
_running = false;
break;
}
}
}
Console.WriteLine("Not correct");
}
// one handler for all buttons. Use the .Tag property to store 0, 1, 2, 3
public void ButtonClick(object sender, EventArgs e)
{
if(!_inputEnabled)
return;
var button = (Button)sender;
// add user input to the queue
_userInput.Add((int)button.Tag);
if(_userInput.Count >= _sequence.Count)
_userInputReady.SetResult(null);
}

How to Pass and Set values to Usercontrol in wpf

How to Pass and Set values to Usercontrol.
Here I have two question regarding a WPF project.
Overview:
In this project, I'm trying to use a Usercontrol as a resources on a canvas and connecting them with each other by LineGeometry. 'MyThumb' class i'm using to make control dragable and control set values.
where i'm using overrided 'OnApplyTemplate' method to pass values on the Usercontrol. To set value i'm using 'Template.FindName'. Here it is returning null.
Now the question is 'how to set values on usercontrol' in the code below:
Another question is related to line color. In the project i'm using LineGeometry to display lines between usercontrols but not able to change line colors.. want to set different lines with different color.
Here the question is how to change color of existing LineGeometry.
Please have a look to the codes i'm using:
Mythumb.cs
public class MyThumb : Thumb
{
#region Properties
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyThumb), new UIPropertyMetadata(""));
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(string), typeof(MyThumb), new UIPropertyMetadata(""));
// This property will hanlde the content of the textblock element taken from control template
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
// This property will handle the content of the image element taken from control template
public string ImageSource
{
get { return (string)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
public Point MyLocation
{
get
{
Point nm = new Point(Canvas.GetLeft(this), Canvas.GetTop(this));
return nm;
}
}
public List<LineGeometry> EndLines { get; private set; }
public List<LineGeometry> StartLines { get; private set; }
#endregion
#region Constructors
public MyThumb()
: base()
{
StartLines = new List<LineGeometry>();
EndLines = new List<LineGeometry>();
}
public MyThumb(string title, string imageSource, Point position)
: this()
{
//Setting ControlTemplate as Usercontrol 'ContactNode'
ControlTemplate templatex = new ControlTemplate();
var fec = new FrameworkElementFactory(typeof(ContactNode));
templatex.VisualTree = fec;
this.Template = templatex;
this.Title = (title != null) ? title : string.Empty;
this.ImageSource = (imageSource != null) ? imageSource : string.Empty;
this.SetPosition(position);
}
public MyThumb( string title, string imageSource, Point position, DragDeltaEventHandler dragDelta)
: this(title, imageSource, position)
{
this.DragDelta += dragDelta;
}
#endregion
// Helper method for setting the position of our thumb
public void SetPosition(Point value)
{
Canvas.SetLeft(this, value.X);
Canvas.SetTop(this, value.Y);
}
#region Linking logic
// This method establishes a link between current thumb and specified thumb.
// Returns a line geometry with updated positions to be processed outside.
public LineGeometry LinkTo(MyThumb target)
{
// Create new line geometry
LineGeometry line = new LineGeometry();
// Save as starting line for current thumb
this.StartLines.Add(line);
// Save as ending line for target thumb
target.EndLines.Add(line);
// Ensure both tumbs the latest layout
this.UpdateLayout();
target.UpdateLayout();
// Update line position
line.StartPoint = new Point(Canvas.GetLeft(this) + this.ActualWidth / 2, Canvas.GetTop(this) + this.ActualHeight / 2);
line.EndPoint = new Point(Canvas.GetLeft(target) + target.ActualWidth / 2, Canvas.GetTop(target) + target.ActualHeight / 2);
// return line for further processing
return line;
}
// This method establishes a link between current thumb and target thumb using a predefined line geometry
// Note: this is commonly to be used for drawing links with mouse when the line object is predefined outside this class
public bool LinkTo(MyThumb target, LineGeometry line)
{
// Save as starting line for current thumb
this.StartLines.Add(line);
// Save as ending line for target thumb
target.EndLines.Add(line);
// Ensure both tumbs the latest layout
this.UpdateLayout();
target.UpdateLayout();
// Update line position
line.StartPoint = new Point(Canvas.GetLeft(this) + this.ActualWidth / 2, Canvas.GetTop(this) + this.ActualHeight / 2);
line.EndPoint = new Point(Canvas.GetLeft(target) + target.ActualWidth / 2, Canvas.GetTop(target) + target.ActualHeight / 2);
return true;
}
#endregion
// This method updates all the starting and ending lines assigned for the given thumb
// according to the latest known thumb position on the canvas
public void UpdateLinks()
{
double left = Canvas.GetLeft(this);
double top = Canvas.GetTop(this);
for (int i = 0; i < this.StartLines.Count; i++)
this.StartLines[i].StartPoint = new Point(left + this.ActualWidth / 2, top + this.ActualHeight / 2);
for (int i = 0; i < this.EndLines.Count; i++)
this.EndLines[i].EndPoint = new Point(left + this.ActualWidth / 2, top + this.ActualHeight / 2);
}
// Upon applying template we apply the "Title" and "ImageSource" properties to the template elements.
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Access the textblock element of template and assign it if Title property defined
if (this.Title != string.Empty)
{
TextBlock txt = this.Template.FindName("tplTextBlock", this) as TextBlock;
if (txt != null) //getting null here unable to find element..
txt.Text = Title;
}
// Access the image element of our custom template and assign it if ImageSource property defined
if (this.ImageSource != string.Empty)
{
Image img = this.Template.FindName("tplImage", this) as Image;
if (img != null)
img.Source = new BitmapImage(new Uri(this.ImageSource, UriKind.Relative));
}
}
}
Window1.xaml.cs
public partial class Window1 : Window
{
// flag for enabling "New thumb" mode
bool isAddNewAction = false;
// flag for enabling "New link" mode
bool isAddNewLink = false;
// flag that indicates that the link drawing with a mouse started
bool isLinkStarted = false;
// variable to hold the thumb drawing started from
MyThumb linkedThumb;
// Line drawn by the mouse before connection established
LineGeometry link;
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Point pp = new Point(myCanvas.ActualWidth/2,myCanvas.ActualHeight/2);
AdNewNode(pp, "ACTION", "/Images/gear_connection.png");
this.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Window1_PreviewMouseLeftButtonDown);
this.PreviewMouseMove += new MouseEventHandler(Window1_PreviewMouseMove);
this.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(Window1_PreviewMouseLeftButtonUp);
}
// Event hanlder for dragging functionality support
private void onDragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
// Exit dragging operation during adding new link
if (isAddNewLink) return;
MyThumb thumb = e.Source as MyThumb;
Canvas.SetLeft(thumb, Canvas.GetLeft(thumb) + e.HorizontalChange);
Canvas.SetTop(thumb, Canvas.GetTop(thumb) + e.VerticalChange);
// Update links' layouts for active thumb
thumb.UpdateLinks();
}
// Event handler for creating new thumb element by left mouse click
// and visually connecting it to the myThumb2 element
void AdNewNode(Point nPosition,string nTitle, string nImage)
{
MyThumb newThumb = new MyThumb(
nTitle,
nImage,
nPosition,
onDragDelta);
myCanvas.Children.Add(newThumb);
}
void Window1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// If adding new action...
if (isAddNewAction)
{
AdNewNode(e.GetPosition(this), "ACTION", "/Images/gear_connection.png");
// resume common layout for application
isAddNewAction = false;
Mouse.OverrideCursor = null;
btnNewAction.IsEnabled = btnNewLink.IsEnabled = true;
e.Handled = true;
}
// Is adding new link and a thumb object is clicked...
if (isAddNewLink && e.Source.GetType() == typeof(MyThumb))
{
if (!isLinkStarted)
{
if (link == null || link.EndPoint != link.StartPoint)
{
Point position = e.GetPosition(this);
link = new LineGeometry(position, position);
//nodepath=new Path();
//nodepath.Stroke = Brushes.Pink;
//nodepath.Data = link; // Here line color is getting change but connectivity getting lost....
connectors.Children.Add(link);
//myCanvas.Children.Add(nodepath);
isLinkStarted = true;
linkedThumb = e.Source as MyThumb;
e.Handled = true;
}
}
}
}
// Handles the mouse move event when dragging/drawing the new connection link
void Window1_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (isAddNewLink && isLinkStarted)
{
// Set the new link end point to current mouse position
link.EndPoint = e.GetPosition(this);
e.Handled = true;
}
}
// Handles the mouse up event applying the new connection link or resetting it
void Window1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// If "Add link" mode enabled and line drawing started (line placed to canvas)
if (isAddNewLink && isLinkStarted)
{
// declare the linking state
bool linked = false;
// We released the button on MyThumb object
if (e.Source.GetType() == typeof(MyThumb))
{
MyThumb targetThumb = e.Source as MyThumb;
// define the final endpoint of line
link.EndPoint = e.GetPosition(this);
// if any line was drawn (avoid just clicking on the thumb)
if (link.EndPoint != link.StartPoint && linkedThumb != targetThumb)
{
// establish connection
linkedThumb.LinkTo(targetThumb, link);
// set linked state to true
//nodepath = new Path();
//nodepath.Stroke = Brushes.Pink;
//nodepath.Data = link;
linked = true;
}
}
// if we didn't manage to approve the linking state
// button is not released on MyThumb object or double-clicking was performed
if (!linked)
{
// remove line from the canvas
//connectors.Children.Remove(link);
// clear the link variable
link = null;
}
// exit link drawing mode
isLinkStarted = isAddNewLink = false;
// configure GUI
btnNewAction.IsEnabled = btnNewLink.IsEnabled = true;
Mouse.OverrideCursor = null;
e.Handled = true;
}
//this.Title = "Links established: " + connectors.Children.Count.ToString();
}
// Event handler for enabling new thumb creation by left mouse button click
private void btnNewAction_Click(object sender, RoutedEventArgs e)
{
isAddNewAction = true;
Mouse.OverrideCursor = Cursors.SizeAll;
btnNewAction.IsEnabled = btnNewLink.IsEnabled = false;
}
private void btnNewLink_Click(object sender, RoutedEventArgs e)
{
isAddNewLink = true;
Mouse.OverrideCursor = Cursors.Cross;
btnNewAction.IsEnabled = btnNewLink.IsEnabled = false;
}
}
Please try to correct me where i'm doing wrong in this code.

Trying to make a custom print class where the application tells when to print a page

I'm building a series of apps for my place of business so I'm trying to create my own printing class that I can refer to for all of my applications.
The issue is, I'm trying to figure out a way for the application to tell the class when to print the page, and I am unable to find a way to do so.
For example, this is what I have so far:
// Report Variables
private bool bPrinting = false;
private int iPage = 0;
private float fOverflow = 0.00F;
private string sPrintLine = null;
private Font fontTmpFont = null;
private PrintPageEventArgs ppeaEv = null;
private Margins mMargins = new System.Drawing.Printing.Margins(25, 25, 25, 25); // Set wide margins
// Clear the print line
public void LineClear()
{
sPrintLine = null;
}
// Insert a string into the print line at the specified position within the line
public void LineInsert(string _InsertString, int _InsertPosition)
{
if (sPrintLine.Length <= _InsertPosition)
sPrintLine = sPrintLine.PadLeft(_InsertPosition) + _InsertString;
else if (sPrintLine.Length <= (_InsertPosition + _InsertString.Length))
sPrintLine = sPrintLine.Substring(0, _InsertPosition) + _InsertString;
else
sPrintLine = sPrintLine.Substring(0, _InsertPosition) + _InsertString + sPrintLine.Substring(_InsertPosition + _InsertString.Length);
}
// Check to see if the line we're trying to print is at the end of the page
public bool AtEndOfPage()
{
return AtEndOfPage(new Font("Courier", 10));
}
public bool AtEndOfPage(Font _Font)
{
if ((fOverflow + _Font.GetHeight(ppeaEv.Graphics)) > ppeaEv.MarginBounds.Height)
return true;
else
return false;
}
// Attempt to print the line
public void LinePrint()
{
LinePrint(null, null);
}
public void LinePrint(Font _Font)
{
LinePrint(_Font, null);
}
public void LinePrint(Font _Font, Brush _Color)
{
if (_Font == null)
_Font = new Font("Courier", 10);
if (_Color == null)
_Color = Brushes.Black;
ppeaEv.Graphics.DrawString(sPrintLine, _Font, _Color,
ppeaEv.MarginBounds.Left, ppeaEv.MarginBounds.Top + fOverflow,
new StringFormat()); // 'Draw' line on page
fOverflow += _Font.GetHeight(ppeaEv.Graphics);
}
// We are done with the report, tell the Print Service to finish up
public void EndReport()
{
ppeaEv.HasMorePages = false;
}
// This is what gets called when the user clicks on 'Print'
private void Print_Click(object sender, EventArgs e)
{
PrintDocument printDocument = new PrintDocument();
printDocument.DefaultPageSettings.Margins = mMargins; // Set margins for pages
printDocument.DefaultPageSettings.Landscape = false; // Set Portrait mode
printDocument.BeginPrint += new PrintEventHandler(printDocument_BeginPrint);
printDocument.EndPrint += new PrintEventHandler(printDocument_EndPrint);
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printDocument; // Set the Document for this print dialog
printDialog.AllowSomePages = true; // Allow the user to select only some pages to print
printDialog.ShowHelp = true; // Allow help button
DialogResult result = printDialog.ShowDialog();
if (result == DialogResult.OK)
{
printDocument.Print(); // Raises PrintPage event
}
printDocument.Dispose();
printDialog.Dispose();
}
void printDocument_BeginPrint(object sender, PrintEventArgs e)
{
iPage = 0;
fOverflow = 0.00F;
}
void printDocument_EndPrint(object sender, PrintEventArgs e)
{
}
As you may be able to tell, I'm trying to fill the page externally to the class, and then have the app tell the class when to print the page when "AtEndOfPage"
I know about "printDocument.PrintPage", but that doesn't seem to be what I need; It builds the page internal to the method and then prints it. I'm not going to be building the print page within that method.
I also am trying to allow for multiple fonts on a single page.
Is there a way to do this?
Thank you all in advance,
Robert

video streaming from android to media player in C#

i want to make a simple video streaming. the application i used is android and simple media player using c#. most of the code i review will have POST method to the ip server. meanwhile my application is using gsm network which it will require to use data packet in transferring data media.
my first step is having an android application which can be record. this step is done. this is my code.
public class Videotest1Activity extends Activity implements
SurfaceHolder.Callback, OnInfoListener, OnErrorListener{
Camera camera;
VideoView videoView;
SurfaceHolder holder;
TextView msg;
Button initBtn, startBtn, stopBtn, playBtn, stprevBtn;
MediaRecorder recorder;
String outputFileName;
static final String TAG = "RecordVideo";
int maxDuration = 7000;//7sec
int frameRate = 1;//15
String serverIP = "172.19.117.12";
int serverPort = 2000;
Socket socket;
int mCount;
//TimerThread mTimer;
Chronometer chronometer;
LocalSocket receiver,sender;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videotest1);
videoView = (VideoView) findViewById(R.id.videoView1);
initBtn = (Button) findViewById(R.id.initialize);
startBtn = (Button) findViewById(R.id.button1);
stopBtn = (Button) findViewById(R.id.button3);
msg = (TextView) findViewById(R.id.textView1);
playBtn = (Button) findViewById(R.id.reviewBtn);
stprevBtn = (Button) findViewById(R.id.stprevBtn);
chronometer = (Chronometer) findViewById(R.id.chronometer1);
/*
mTimer= new TimerThread();
mTimer.setOnAlarmListener(mSTimer_OnAlarm);
mTimer.setPeriod(100);
*/
}
public void buttonTapped(View view){
switch(view.getId()){
case R.id.initialize:
initRecorder();
break;
case R.id.button1:
beginRecording();
break;
case R.id.button3:
stopRecording();
break;
case R.id.reviewBtn:
playRecording();
break;
case R.id.stprevBtn:
stopPlayback();
break;
}
}
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Log.e(TAG, "Record error");
stopRecording();
Toast.makeText(this, "Recording limit reached", 2500).show();
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Log.i(TAG, "recording event");
if(what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED){
Log.i(TAG, "...max duration reached");
stopRecording();
Toast.makeText(this, "Recording limit info", 2500).show();
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
Log.v(TAG, "in surfaceCreated");
try{
camera.setPreviewDisplay(holder);
camera.startPreview();
}catch(IOException e){
Log.v(TAG, "Could not start the preview");
e.printStackTrace();
}
initBtn.setEnabled(true);
startBtn.setEnabled(true);
stopBtn.setEnabled(true);
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
protected void onResume(){
Log.v(TAG, "in onResume");
super.onResume();
initBtn.setEnabled(false);
startBtn.setEnabled(false);
stopBtn.setEnabled(false);
playBtn.setEnabled(false);
stprevBtn.setEnabled(false);
if(!initCamera())
finish();
}
public boolean initCamera(){
try{
camera = Camera.open();
Camera.Parameters camParam = camera.getParameters();
camera.lock();
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//Thread thread = new Thread(new hantarThread());
//thread.start();
}catch(RuntimeException re){
Log.v(TAG, "Could not initialize the camera");
re.printStackTrace();
return false;
}
return true;
}
public void initRecorder(){
if(recorder != null)return;
outputFileName = Environment.getExternalStorageDirectory() + "/videooutput.mp4";
File outputFile = new File(outputFileName);
if(outputFile.exists())
outputFile.delete();//knp nk dlt?
try{
Toast.makeText(this, "InitRecord", 2500).show();
camera.stopPreview();
camera.unlock();
recorder = new MediaRecorder();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setVideoSize(176, 144);
recorder.setVideoFrameRate(15);//15
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//mpeg_4
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setMaxDuration(60000);
recorder.setPreviewDisplay(holder.getSurface());
recorder.setOutputFile(outputFileName);
recorder.prepare();
Log.v(TAG, "MediaRecorder initialized");
initBtn.setEnabled(false);
startBtn.setEnabled(true);
}catch(Exception e){
Log.v(TAG, "MediaRecorder failed");
e.printStackTrace();
}
}
public void beginRecording(){
//mCount = 0;
//mTimer.start();
try{
Log.v(TAG, "start Recording begin");
int stoppedMilliseconds = 0;
String chronoText = chronometer.getText().toString();
String array[] = chronoText.split(":");
if (array.length == 2) {
stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 1000
+ Integer.parseInt(array[1]) * 1000;
} else if (array.length == 3) {
stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 60 * 1000
+ Integer.parseInt(array[1]) * 60 * 1000
+ Integer.parseInt(array[2]) * 1000;
}
chronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
//chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
Log.v(TAG, "timer start");
long dTime = chronometer.getDrawingTime();
long autoLink = chronometer.getAutoLinkMask();
Log.v(TAG, "getDrawingTime: " + dTime);
Log.v(TAG, "AutoLink: " + autoLink);
recorder.setOnInfoListener(this);
recorder.setOnErrorListener(this);
recorder.start();
msg.setText("Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
}catch(Exception e){
Log.v(TAG, "start Recording failed");
e.printStackTrace();
}
}
public void stopRecording(){
if(recorder != null){
recorder.setOnErrorListener(null);
recorder.setOnInfoListener(null);
try{
recorder.stop();
Log.v(TAG, "stop Record Begin");
chronometer.stop();
Log.v(TAG, "Timer stop");
//mTimer.stop();
}catch(IllegalStateException e){
Log.e(TAG, "stop is ILLEGAL");
}
releaseRecorder();
msg.setText("");
releaseCamera();
startBtn.setEnabled(false);
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
}
else{
Log.v(TAG, "video cannot stop. Video null");
long autoLink = chronometer.getAutoLinkMask();
Log.v(TAG, "stop aLink: " + autoLink);
long elapsedMillis = SystemClock.elapsedRealtime() - chronometer.getBase();
Log.v(TAG, "elapsedMillis: " + elapsedMillis);
}
}
private void releaseCamera(){
if(camera != null){
try{
camera.reconnect();
}catch(IOException e){
e.printStackTrace();
}
camera.release();
camera = null;
}
}
private void releaseRecorder(){
if(recorder != null){
recorder.release();
recorder = null;
}
}
private void playRecording(){
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoPath(outputFileName);
videoView.start();
stprevBtn.setEnabled(true);
}
private void stopPlayback(){
videoView.stopPlayback();
}
}
}
next step i make is makes the media player can be play videooutput.mp4. in here, to make it play, it first must load the video then played. well, this is for the second step. it works well too. here's my code.
private void button6_Click_1(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// create video source
FileVideoSource fileSource = new FileVideoSource(openFileDialog1.FileName);
// open it
OpenVideoSource(fileSource);
}
}
// Open video source
private void OpenVideoSource(IVideoSource source)
{
// set busy cursor
this.Cursor = Cursors.WaitCursor;
// stop current video source
CloseCurrentVideoSource();
// start new video source
videoSourcePlayer.VideoSource = source;
videoSourcePlayer.Start();
// reset stop watch
stopWatch = null;
// start timer
videoTimer.Start();
this.Cursor = Cursors.Default;
}
// New frame received by the player
private void videoSourcePlayer_NewFrame(object sender, ref Bitmap image)
{
DateTime now = DateTime.Now;
Graphics g = Graphics.FromImage(image);
// paint current time
SolidBrush brush = new SolidBrush(Color.Red);
g.DrawString(now.ToString(), this.Font, brush, new PointF(5, 5));
brush.Dispose();
g.Dispose();
}
// Close video source if it is running
private void CloseCurrentVideoSource()
{
if (videoSourcePlayer.VideoSource != null)
{
videoSourcePlayer.SignalToStop();
// wait ~ 3 seconds
for (int i = 0; i < 30; i++)
{
if (!videoSourcePlayer.IsRunning)
break;
System.Threading.Thread.Sleep(100);
}
if (videoSourcePlayer.IsRunning)
{
videoSourcePlayer.Stop();
}
videoSourcePlayer.VideoSource = null;
}
}
im using AForge for the media player in c#. All i did is adding the reference of AForge.Controls, AForge.Video and AForge.Video.DirectShow.
now, what i need to do is sending the media data to the media player(c#) byte by byte. i dont have a clue how to make this happen. i also found sample coding IP camera android which it bring the video to the server. however, i still dont have a clue to do it in my apps.
note that the gsm will require number phone of the simcard used and also port number of the modem gsm.
can anybody help me with this. or perhaps giving me some idea on modifying the code. any helps is appreciated. thanks for advance.

Categories