MediaRecorder doesn't start in android xamarin - c#

I am developing an app where i can upload videos of upto 2 mins per user.
I want the user to record a video and upload it to the server.I am able to do it with intent but not with media recorder.
The requirement is to not allow user to preview the video and instead record it and when user stops recording, upload the video to server.
(Is it possible to not allow the playback of the recorded video in VIDEO_CAPTURE intent ???)
I am trying to record a video with media recorder. But it throws an exception at MediaRecorder.Start()
Here's the code : -
//Class level variables
Camera PhoneCamera;
VideoView VideoRecorderView;
MediaRecorder VideoRecorder;
Button BtnRecordVideo;
// I start a video recording on click of the button
void RecordVideoWithCustomRecorder(object sender,EventArgs e){
//TODO : Create a custom layout for recording video in one shot and then uplaoding it to kaltura server
if (IsRecording) {
VideoRecorder.Stop ();
ReleaseMediaRecorder ();
PhoneCamera.Lock ();
(sender as Button).SetBackgroundResource (Resource.Drawable.record_red);
StopTimer ();
//UploadVideo
byte[] getBytes = System.IO.File.ReadAllBytes (RecorderFile._file.AbsolutePath);
UploadVideoToKaltura (getBytes);
IsRecording = false;
} else {
ReleaseCamera ();
if (PrepareVideoRecorder ()) {
//System.Threading.Thread.Sleep (1000); i tried putting this, but it won't work
VideoRecorder.Start ();//I get an exception here - not sure why
RunOnUiThread (() => {
(sender as Button).SetBackgroundResource (Resource.Drawable.record_stop);
initTimer2 ();
IsRecording = true;
});
} else {
ReleaseMediaRecorder ();
RunOnUiThread (() => {
AlertDialogManager.ShowDialogWithSingleButton(this,"Video Error","Can't record the video now. Exit the camera and try recording again.","Exit Camera",(()=>{
this.Finish();
}));
});
}
}
}
//Here's the code to prepare the media recorder
bool PrepareVideoRecorder(){
PhoneCamera = IsFrontCameraAvailable ? Camera.Open (1) : Camera.Open ();
VideoRecorder = new MediaRecorder ();
//Unlock & set camera to media recorder
PhoneCamera.Unlock ();
VideoRecorder.SetCamera (PhoneCamera);
//Set Source - Video and audio
VideoRecorder.SetAudioSource (AudioSource.Camcorder);
VideoRecorder.SetVideoSource (VideoSource.Camera);
//set Camcorder profile
VideoRecorder.SetProfile(CamcorderProfile.Get(CamcorderQuality.High));
//set output file
RecorderFile._file = new File(RecorderFile._dir, String.Format("vm_movie_{0}.mp4", Guid.NewGuid()));
VideoRecorder.SetOutputFile (RecorderFile._file.AbsolutePath);
//set preview display
VideoRecorder.SetPreviewDisplay (VideoRecorderView.Holder.Surface);
//Prepare media recorder
VideoRecorder.SetMaxDuration (12000);
try{
VideoRecorder.Prepare();
}catch(Exception ex){
Utils.WriteDebugInfo ("Excepion -PrepareVideoRecorder: " + ex.Message);
return false;
}
return true;
}
//Release Media Recorder
private void ReleaseMediaRecorder(){
if (VideoRecorder != null) {
VideoRecorder.Reset(); // clear recorder configuration
VideoRecorder.Release(); // release the recorder object
VideoRecorder = null;
PhoneCamera.Lock(); // lock camera for later use
}
}
//Release Camers
private void ReleaseCamera(){
if (PhoneCamera != null){
PhoneCamera.Release ();
// release the camera for other applications
PhoneCamera = null;
}
}
//Creating app specific diary for videos
private void CreateDirectoryForVideos()
{
RecorderFile._dir = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures),"VirtualMentorVideos");
if (!RecorderFile._dir.Exists())
{
RecorderFile._dir.Mkdirs();
}
}

Related

How to Record silence without MIC

I have a desktop application in C# that records audio from MIC using NAudio library. The application starts recording from default input device if MIC is connected to the system. The output wave file is saved.
I want to record silent to the output file if MIC is not connected, How can I feed a dummy MIC or virtual MIC to starts recording from if real mic is not connected.
Thanks
Here's the Code:
class AudioRecorder
{
private WaveIn waveIn = null;
private WaveFileWriter waveWriter = null;
public AudioRecorder()
{
if (WaveIn.DeviceCount > 0) //Means there is a mic
{
waveIn = new WaveIn();
waveIn.DeviceNumber = 0; //default device
waveIn.DataAvailable += WaveIn_DataAvailable;
}
else
{
//I want to add the virtual mic that will send only silent signal
}
}
public void Start()
{
waveIn.StartRecording();
}
public void Stop()
{
waveIn.StopRecording();
}
private void WaveIn_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveWriter == null)
waveWriter = new WaveFileWriter("output.wav", new WaveFormat(44100, 2));
waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
}
}

Windows Media Capture -402587628 error "The text associated with this error code could not be found."

private async Task InitializeCameraAsync()
{
if (_mediaCapture == null)
{
// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
// Get the desired camera by panel
DeviceInformation cameraDevice =
allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null &&
x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
// If there is no camera on the specified panel, get any camera
cameraDevice = cameraDevice ?? allVideoDevices.FirstOrDefault();
if (cameraDevice == null)
{
//ShowMessageToUser("No camera device found.");
Debug.WriteLine("No camera device found.");
return;
}
// Create MediaCapture and its settings
_mediaCapture = new MediaCapture();
// Register for a notification when video recording has reached the maximum time and when something goes wrong
//_mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded;
var mediaInitSettings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
// Initialize MediaCapture
try
{
await _mediaCapture.InitializeAsync(mediaInitSettings);
_isInitialized = true;
}
catch (UnauthorizedAccessException)
{
//ShowMessageToUser("The app was denied access to the camera");
Debug.WriteLine("The app was denied access to the camera");
}
catch (Exception ex)
{
Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", cameraDevice.Id, ex.ToString());
}
// If initialization succeeded, start the preview
if (_isInitialized)
{
// Figure out where the camera is located
if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
{
// No information on the location of the camera, assume it's an external camera, not integrated on the device
_externalCamera = true;
}
else
{
// Camera is fixed on the device
_externalCamera = false;
// Only mirror the preview if the camera is on the front panel
//_mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
}
//await StartPreviewAsync();
//UpdateCaptureControls();
}
}
}
Problem appears in the second "catch" statement while trying to InitializeAsync mediaCapture.
How can I check what's wrong, if it doesn't provide me any error details?

How to access the camera from my Windows Phone 8 app (XAML and C#) and save the taken picture in a determined folder?

I want the Windows Phone 8 app that I am building at this moment to access the camera for taking a photo when a concrete button on the screen is pressed and then save the image that has been taken into a determined folfer (a folder created into the Windows Phone project by me, not the Windows Phone default image gallery).
Could you help me accesing the camera, taking the picture and saving it into the folder created by me, please? I am using XAML and C#.
Thank you so much!!!
I would recommend PhotoCamera class if capture is to be processed on a button in the app
PhotoCamera myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
//viewfinderBrush is a videobrush object declared in xaml
viewfinderBrush.SetSource(myCamera);
myCamera.Initialized += myCamera_Initialized;
myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable);
//Events
void myCamera_Initialized(object sender, CameraOperationCompletedEventArgs e)
{
try
{
if (e.Succeeded)
{
}
}
catch
{
MessageBox.Show("Problem occured in camera initialization.");
}
}
void camera_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
{
try
{
}
catch
{
MessageBox.Show("Captured image is not available, please try again.");
}
}
void camera_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
try
{
}
catch (Exception ex)
{
MessageBox.Show("Captured image is not available, please try again. " + ex.Message);
}
}
And there is one more alternative called CameraCaptureTask
CameraCaptureTask cameraCaptureTask;
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
cameraCaptureTask.Show();
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
//System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
//bmp.SetSource(e.ChosenPhoto);
//myImage.Source = bmp;
}
}
Check this for PhotoCamera class
And this for CameraCaptureTask
There's a simple code demonstration here showing your to put the camera API to use for Windows Phone8 apps.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)) {
// Initialize the default camera.
_photoCamera = new Microsoft.Devices.PhotoCamera();
//Event is fired when the PhotoCamera object has been initialized
_photoCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(OnPhotoCameraInitialized);
//Set the VideoBrush source to the camera
viewfinderBrush.SetSource(_photoCamera);
}
else {
// The camera is not supported on the device.
this.Dispatcher.BeginInvoke(delegate() {
// Write message.
txtDebug.Text = "A Camera is not available on this device.";
});
}
}
private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e) {
int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
}
Dont forget to add this line in WMAppManifent.xml file.
<Capability Name="ID_CAP_ISV_CAMERA"/>
you can read here ,
Using Cameras in Your Windows Phone Application

Emgu CV check web cam connectivity

I am writing a C# web camera application using Emgu CV. I tried to handle when user unplug the web cam during frame capturing in pictureBox.
If the web camera is unplugged, then the application should start scanning for new web cam connectivity every 2 seconds until the pictureBox can be updated again.
The following timer code could not catch anything, the program initially captures frames, I unplug the camera, then plug back, but the camera can not be restart.
private void timer1_Tick(object sender, EventArgs e)
{
if (cap == null)
{
try
{
cap = new Capture(0);
cap.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 320);
cap.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 240);
Console.WriteLine("Restarting Cam");
}
catch (Exception ee){
Console.WriteLine("null"); cap = null; return;
}
}
else
{
Console.WriteLine("NO null");
}
try
{
Image<Bgr, byte> nextFrame = cap.QueryFrame();
}
catch(Exception ee)
{
Console.WriteLine("Frame Capture fail");
cap.Dispose();
cap = null;
return;
}
using (Image<Bgr, byte> nextFrame = cap.QueryFrame())
{
if (nextFrame != null)
{
Image<Gray, byte> grayframe = nextFrame.Convert<Gray, byte>();
videoBox.Image = nextFrame.ToBitmap();
}
}
}
The program keep printing "No null", 20 second after unplugging the camera, the output console printed out The thread '' (0xb96c) has exited with code 0 (0x0)
You can check connectivity with DirectShow lib. Get an array of all connected cameras first
DirectShowLib.DsDevice[] allCameras = DirectShowLib.DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
add to you class property for selected camera name, and then you can check if camera is connected
bool isConnected = DirectShowLib.DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice).Any(c => c.Name == selectedCameraName);

Record continuously 5min (x-minutes) of video with Microsoft Expression Encoder

My Software is to record continuously 5min of video.
Example: the software should start the recording on program-start and hold continuously 5min of video in buffer. When I stop the recording the last 5min of recording should save to disk
private void CaptureMoni()
{
try
{
Rectangle _screenRectangle = Screen.PrimaryScreen.Bounds;
_screenCaptureJob = new ScreenCaptureJob();
_screenCaptureJob.CaptureRectangle = _screenRectangle;
_screenCaptureJob.ShowFlashingBoundary = true;
_screenCaptureJob.ScreenCaptureVideoProfile.FrameRate = 20;
_screenCaptureJob.CaptureMouseCursor = true;
_screenCaptureJob.OutputScreenCaptureFileName = string.Format(#"C:\test.wmv");
if (File.Exists(_screenCaptureJob.OutputScreenCaptureFileName))
{
File.Delete(_screenCaptureJob.OutputScreenCaptureFileName);
}
_screenCaptureJob.Start();
}
catch(Exception e) { }
}
something like that:
private void SaveRecord(int cntMinutes)
{
try
{
_screenCaptureJob.Stop();
// something like that
_screenCaptureJob.SaveLastXMinutes(cntMinutes);
}
catch(Exception e) { }
}

Categories

Resources