I want to make an ap that turn on the flash when i press the On button, and turn off when I press the Off Button. This is my code :
protected AudioVideoCaptureDevice Device { get; set; }
private async void Button_Click_TurnOn(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
try
{
// get the AudioViceoCaptureDevice
var avDevice = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
}
else
{
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
// ShowWhiteScreenInsteadOfCameraTorch();
}
}
private void Button_Click_TurnOff(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
try
{
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (this.Device != null && supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.Off))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
}
else
{
//turnWhiteScreen(false);
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
//turnWhiteScreen(false);
}
}
I copied it from another question at stackoverflow, but I dont know why this code doesnt work for me. Tested on Lumia 820.
Please help me, thank you very much :)
async private void FlashlightOn_Click(object sender, RoutedEventArgs e)
{
// turn flashlight on
CameraSensorLocation location = CameraSensorLocation.Back;
if (this.audioCaptureDevice == null)
{
audioCaptureDevice = await AudioVideoCaptureDevice.OpenAsync(location,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(location).First());
}
FlashOn(location, VideoTorchMode.On);
}
private void FlashlightOff_Click(object sender, RoutedEventAgrs e)
{
// turn flashlight off
var sensorLocation = CameraSensorLocation.Back;
FlashOn(sensorLocation, VideoTorchMode.Off);
}
public bool FlashOn(CameraSensorLocation location, VideoTorchMode mode)
{
// turn flashlight on/off
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(location, KnownCameraAudioVideoProperties.VideoTorchMode);
if ((audioCaptureDevice != null) && (supportedCameraModes.ToList().Contains((UInt32)mode)))
{
audioCaptureDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, mode);
return true;
}
return false;
}
Related
I have an application where user can click on a Scan button to scan the image to preview in the application. When user clicks, usually a "Preparing to scan" message will be shown and goes away when the scan is 100% complete.
The scan works fine. The problem if I stress test it by pressing the scan button many times while it's doing it's work, the application completely hangs and the message just stays there and I had to restart my whole application.
The code: It's just a small section
private void ScanStripButton_Click(object sender, EventArgs e)
{
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
}
Any idea on how to prevent this issue?
Appreciate the help
EDIT:
public void StartTwainScan()
{
Boolean EnableUI = false;
Boolean ADF = false;
Boolean EnableDuplex = false;
if (Properties.Settings.Default.TwainShow.Equals("1"))
{
EnableUI = true;
}
if (Properties.Settings.Default.ScanType.Equals("2"))
{
ADF = true;
}
if (Properties.Settings.Default.DuplexEnable.Equals("1"))
{
EnableDuplex = true;
}
var rs = new ResolutionSettings
{
Dpi = GetResolution(),
ColourSetting = GetColorType()
};
var pg = new PageSettings()
{
Size = GetPageSize()
};
var settings = new ScanSettings
{
UseDocumentFeeder = ADF,
ShowTwainUI = EnableUI,
ShowProgressIndicatorUI = true,
UseDuplex = EnableDuplex,
Resolution = rs,
Page = pg
};
try
{
TwainHandler.StartScanning(settings);
}
catch (TwainException ex)
{
MessageBox.Show(ex.Message);
//Enabled = true;
//BringToFront();
}
}
This isn't going to be the correct answer, but you haven't shown enough code to give you the right code. It should point you in the right direction.
private void ScanStripButton_Click(object sender, EventArgs e)
{
ScanStripButton.Enabled = false;
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
ScanStripButton.Enabled = true;
}
Basically you disable the button when the scan starts and enable it when it finishes.
private async void ScanStripButton_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
});
}
or
private bool clicked = false;
private void ScanStripButton_Click(object sender, EventArgs e)
{
try
{
if(clicked)
return;
clicked = true;
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
}
finally
{
clicked = false;
}
}
I'm working on a text to speech demo, in which I'm using speech synthesizer.
My problem is when I click on play button the page is loading continuously.
It does not stop even if the speech is finished. Also in my demo pause and resume are not working.
I also tried to use spVoice interface for text to speech, but in this demo also pause and resume are not working.
Demo Using Speech synthesizer -
SpeechSynthesizer spRead;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Creating new object of SpeechSynthesizer.
spRead = new SpeechSynthesizer();
}
} // Page_Load
protected void btnPlay_Click(object sender, EventArgs e)
{
// Get the content data as per the content id
_contentData = new ContentFormData(ContentManager.GetContentData(Page.Database, ContentId, Page.IsLive));
// Get the text after trim
_speechText = WebUtility.HtmlDecode(_contentData.Content.Text1.Trim());
// If Speech Text is not null
// then check the button class, if cssclass is play change it to pause
and call speak method.
if (_speechText != null && !string.IsNullOrEmpty(_speechText))
{
// if button is play buttton
// then call play method and speech the text
if (btnPlay.CssClass == "button-play")
{
btnPlay.CssClass = btnPlay.CssClass.Replace("button-play",
"button-pause");
// creating the object of SpeechSynthesizer class
spRead = new SpeechSynthesizer();
spRead.SpeakAsync(_speechText);
spRead.SpeakCompleted += new
EventHandler<SpeakCompletedEventArgs>(spRead_SpeakCompleted);
}
// If button class is pause
// then change it to continue and call pause method.
else if (btnPlay.CssClass == "button-pause")
{
btnPlay.CssClass = btnPlay.CssClass.Replace("button-pause",
"button-continue");
if (spRead != null)
{
// Check the state of spRead, and call pause method.
if (spRead.State == SynthesizerState.Speaking)
{
spRead.Pause();
}
}
btnPlayFromStart.Enabled = true;
}
// If button class is continue
// then change it to pause and call resume method.
else if (btnPlay.CssClass == "button-continue")
{
btnPlay.CssClass = btnPlay.CssClass.Replace("button-continue",
"button-pause");
if (spRead != null)
{
// Check the state of spRead, and call resume method.
if (spRead.State == SynthesizerState.Paused)
{
spRead.Resume();
}
}
btnPlayFromStart.Enabled = false;
}
}
}
private void spRead_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
// If Spread is not null
// then dispose the spread after the speak is completed
// else do nothing
if (spRead != null)
{
spRead.Dispose();
}
else
{
// do nothing
}
} // spRead_SpeakCompleted
Demo Using SpVoice -
SpVoice voice;
protected void Page_Load(object sender, EventArgs e)
{
_contentData = new
ContentFormData(ContentManager.GetContentData(Page.Database, ContentId,
Page.IsLive));
_speechText = WebUtility.HtmlDecode(_contentData.Content.Text1.Trim());
} // Page_Load
protected void btnPlay_Click(object sender, EventArgs e)
{
voice = new SpVoice();
if (btnPlay.CssClass == "button-play")
{
voice.Speak(_speechText, SpeechVoiceSpeakFlags.SVSFlagsAsync);
btnPlay.CssClass = btnPlay.CssClass.Replace("button-play", "button-
pause");
}
else if (btnPlay.CssClass == "button-pause")
{
voice.Pause();
btnPlay.CssClass = btnPlay.CssClass.Replace("button-pause", "button-
continue");
}
else if (btnPlay.CssClass == "button-continue")
{
voice.Resume();
btnPlay.CssClass = btnPlay.CssClass.Replace("button-continue",
"button-play");
}
}
Solved the issue by using handeler, to stop the postback.
Stored the voice object in session and in pause and resume get the voice object from session.
Please someone can access to a ip camera with emgucv in c# visual studio in other post share the code
capture = new Emgu.CV.CvInvoke.cvCreateFileCapture("Url ip camera");
when i run the code say"the tipe cvCreateFileCapture does not exist in CvInvoke"
someone know other form to access an ip camera with emgucv but working...thanks!
this is my exmaple, it works with me, I a using EmguCV V3
public partial class Form1 : Form
{
private Capture _capture = null;
private bool _captureInProgress;
public Form1()
{
InitializeComponent();
CvInvoke.UseOpenCL = false;
try
{
_capture = new Capture("http://webcam.st-malo.com/axis-cgi/mjpg/video.cgi?");//
_capture.ImageGrabbed += ProcessFrame;
}
catch (NullReferenceException excpt)
{
MessageBox.Show(excpt.Message);
}
}
private void ProcessFrame(object sender, EventArgs arg)
{
Mat frame = new Mat();
_capture.Retrieve(frame, 0);
captureImageBox.Image = frame;
}
private void captureButton_Click(object sender, EventArgs e)
{
if (_capture != null)
{
if (_captureInProgress)
{ //stop the capture
captureButton.Text = "Start Capture";
_capture.Pause();
}
else
{
//start the capture
captureButton.Text = "Stop";
_capture.Start();
}
_captureInProgress = !_captureInProgress;
}
}
}
I have one simple application for Kinect but it seems it consumes a lot of resources. It works normally for a 1-2 minutes and then lag becomes unbearable.
This is my configuration:
Intel Core i3 CPU M330 2.13 GHz
4 GB RAM
ATI Radeon HD 4570
This is code for application window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
this.WindowState = System.Windows.WindowState.Maximized;
}
private void StopKinect(KinectSensor sensor)
{
if (sensor != null)
{
if (sensor.IsRunning)
{
//stop sensor
sensor.Stop();
//stop audio if not null
if (sensor.AudioSource != null)
{
sensor.AudioSource.Stop();
}
}
}
}
private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
{
StopKinect(Generics.GlobalKinectSensorChooser.Kinect);
}
}
This is code for main menu (first screen):
public partial class MainMenu : Page
{
#region "Kinect"
private KinectSensorChooser sensorChooser;
#endregion
public MainMenu()
{
this.InitializeComponent();
if (Generics.GlobalKinectSensorChooser == null)
{
// initialize the sensor chooser and UI
this.sensorChooser = new KinectSensorChooser();
this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged;
this.sensorChooserUi.KinectSensorChooser = this.sensorChooser;
this.sensorChooser.Start();
Generics.GlobalKinectSensorChooser = this.sensorChooser;
}
else
{ // initialize the sensor chooser and UI
this.sensorChooser = new KinectSensorChooser();
this.sensorChooser = Generics.GlobalKinectSensorChooser;
this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged;
this.sensorChooserUi.KinectSensorChooser = sensorChooser;
}
// Bind the sensor chooser's current sensor to the KinectRegion
var regionSensorBinding = new Binding("Kinect") { Source = this.sensorChooser };
BindingOperations.SetBinding(this.kinectRegion, KinectRegion.KinectSensorProperty, regionSensorBinding);
}
private void SensorChooserOnKinectChanged(object sender, KinectChangedEventArgs args)
{
bool error = false;
if (args.OldSensor != null)
{
try
{
args.OldSensor.DepthStream.Range = DepthRange.Default;
args.OldSensor.SkeletonStream.EnableTrackingInNearRange = false;
args.OldSensor.DepthStream.Disable();
args.OldSensor.SkeletonStream.Disable();
args.OldSensor.ColorStream.Disable();
}
catch (InvalidOperationException)
{
// KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
// E.g.: sensor might be abruptly unplugged.
error = true;
}
}
if (args.NewSensor != null)
{
try
{
args.NewSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
args.NewSensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
args.NewSensor.SkeletonStream.Enable();
}
catch (InvalidOperationException)
{
error = true;
}
}
if (!error)
kinectRegion.KinectSensor = args.NewSensor;
}
private void Screen1ButtonOnClick(object sender, RoutedEventArgs e)
{
this.sensorChooser.KinectChanged -= SensorChooserOnKinectChanged;
(Application.Current.MainWindow.FindName("_mainFrame") as Frame).Source = new Uri("Depth.xaml", UriKind.Relative);
}
}
And this code for screen1:
public partial class Depth : Page
{
#region "Kinect"
private KinectSensorChooser sensorChooser;
#endregion
const float MaxDepthDistance = 4095; // max value returned
const float MinDepthDistance = 850; // min value returned
const float MaxDepthDistanceOffset = MaxDepthDistance - MinDepthDistance;
public Depth()
{
this.InitializeComponent();
// initialize the sensor chooser and UI
this.sensorChooser = new KinectSensorChooser();
//Assign the sensor chooser with the sensor chooser from the mainwindow.
//We are reusing the sensorchoosing declared in the first window that can in contact with kinect
this.sensorChooser = Generics.GlobalKinectSensorChooser;
//subscribe to the sensorChooserOnKinectChanged event
this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged;
//Assign Kinect Sensorchooser to the sensorchooser we got from our static class
this.sensorChooserUi.KinectSensorChooser = sensorChooser;
// Bind the sensor chooser's current sensor to the KinectRegion
var regionSensorBinding = new Binding("Kinect") { Source = this.sensorChooser };
BindingOperations.SetBinding(this.kinectRegion, KinectRegion.KinectSensorProperty, regionSensorBinding);
}
private void SensorChooserOnKinectChanged(object sender, KinectChangedEventArgs args)
{
bool error = false;
if (args.OldSensor != null)
{
try
{
args.OldSensor.DepthStream.Range = DepthRange.Default;
args.OldSensor.SkeletonStream.EnableTrackingInNearRange = false;
args.OldSensor.DepthStream.Disable();
args.OldSensor.SkeletonStream.Disable();
args.OldSensor.ColorStream.Disable();
}
catch (InvalidOperationException)
{
error = true;
}
}
if (args.NewSensor != null)
{
try
{
args.NewSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
args.NewSensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
args.NewSensor.SkeletonStream.Enable();
}
catch (InvalidOperationException)
{
error = true;
}
}
if (!error)
kinectRegion.KinectSensor = args.NewSensor;
}
private void MenuButtonOnClick(object sender, RoutedEventArgs e)
{
//Unsubscribe to the sensorchooser's event SensorChooseronkinectChanged
this.sensorChooser.KinectChanged -= SensorChooserOnKinectChanged;
(Application.Current.MainWindow.FindName("_mainFrame") as Frame).Source = new Uri("MainScreen.xaml", UriKind.Relative);
}
}
There are a couple of more screens, I choosed this screen where I'm using KinectDepthViewer from WpfViewers. This screen has the worst lag, application is unusable almost instantly. Other screens where I have just buttons don't have a lag at the beginning but they get it after 2-3 minutes of usage.
I don't know am I doing something wrong in initialization maybe. I hope someone has some advice. I've read that people didn't have problems with development on even weaker configurations so I hope it's not because of that.
Thank you!
your graphics adapter suggests you're using a notebook computer. While there might be something in your code that could be improved, I really think the problem is your hardware. Notebooks with the specs you listed will have trouble running something as CPU intensive as what you're trying to do with the Kinect.
I'm experimenting on how to play mp3 using Naudio. My simple app has one windows form and one button to play/pause the music. The app however has two major problem:
While it was intended that if the music is playing and the play button is pressed, the app should stop playing. Instead when the button is re-pressed, the app restart the music and then (sometime) throw an exception
If the button is pressed two or three times (and without any delay) ,the app throw a NAudio.MmException (Message=InvalidParameter calling acmStreamClose)
Can someone tell me what's wrong with my code? Below is my code:
using System;
using System.Windows.Forms;
namespace NaudioTesting
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private NAudio.Wave.BlockAlignReductionStream stream = null;
private NAudio.Wave.DirectSoundOut output = null;
public void LoadFile(string filePath)
{
DisposeWave();
if (filePath.EndsWith(".mp3"))
{
NAudio.Wave.WaveStream pcm =
NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(filePath));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
else if (filePath.EndsWith(".wav"))
{
NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(filePath));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
else throw new InvalidOperationException("Not a correct audio file type.");
output = new NAudio.Wave.DirectSoundOut();
output.Init(stream);
output.Play();
}
private void playPauseButton_Click(object sender, EventArgs e)
{
string filePath = "GetLoud.mp3";
LoadFile(filePath);
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Pause();
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused) output.Play();
}
}
private void DisposeWave()
{
try
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Stop();
output.Dispose();
output = null;
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
}
catch (NAudio.MmException)
{
throw;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DisposeWave();
}
}
}
Looking at the DirectSoundOut source, the implementation for Play and Pause doesn't support resuming. Namely, what happens to you is exactly what it should. Calling play will always start from begining of the stream.
You should use WaveOut instead. It supports resuming by calling Play again, just like what you have in your code.
output = new NAudio.Wave.WaveOut();