NullReference when importing custom midis on UnitySynth - c#

So, I downloaded the unity project from unity answers.
here is the link:
UnitySynth link to download page in unity answers
I have finished my prototype, but I'm getting errors when I tried to load a custom midi I downloaded from the web.
I got these error codes:
Error Loading Midi:
Midi Failed to Load!
UnityEngine.Debug:Log(Object)
CSharpSynth.Sequencer.MidiSequencer:LoadMidi(String, Boolean) (at Assets/Plugins/CSharpSynth/Sequencer/MidiSequencer.cs:153)
UnitySynthTest:Awake() (at Assets/Scripts/UnitySynthTest.cs:42)
NullReferenceException: Object reference not set to an instance of an object
CSharpSynth.Sequencer.MidiSequencer.Play () (at Assets/Plugins/CSharpSynth/Sequencer/MidiSequencer.cs:167)
UnitySynthTest.OnGUI () (at Assets/Scripts/UnitySynthTest.cs:161)
I would love to know an easy way to convert midis to mid.txt as the examples used in the demo.
EDIT:
The first error code, the one about not loading midi, comes from here:
public bool LoadMidi(string file, bool UnloadUnusedInstruments)
{
if (playing == true)
return false;
MidiFile mf = null;
try
{
mf = new MidiFile(file);
}
catch (Exception ex)
{
//UnitySynth
//THIS IS THE ERROR LINE **************************
Debug.Log("Error Loading Midi:\n" + ex.Message);
return false;
}
return LoadMidi(mf, UnloadUnusedInstruments);
}
The second one, the one about null reference exception comes from:
public void Play()
{
if (playing == true)
return;
//Clear the current programs for the channels.
Array.Clear(currentPrograms, 0, currentPrograms.Length);
//Clear vol, pan, and tune
ResetControllers();
//set bpm
// THIS IS THE ERROR LINE *****************************
_MidiFile.BeatsPerMinute = 120;
//Let the synth know that the sequencer is ready.
eventIndex = 0;
playing = true;
}

I solved my own question by removing the try and catch elements in the code, like this:
public bool LoadMidi(string file, bool UnloadUnusedInstruments)
{
MidiFile mf = File.Open(file, FileMode.Open);
return LoadMidi(mf, UnloadUnusedInstruments);
}
I dunno what happens here and if I should do that, but now even non .mid.txt files can be reproduced without problems.

Related

Why does my file sometimes disappear in the process of reading from it or writing to it?

I have an app that reads from text files to determine which reports should be generated. It works as it should most of the time, but once in awhile, the program deletes one of the text files it reads from/writes to. Then an exception is thrown ("Could not find file") and progress ceases.
Here is some pertinent code.
First, reading from the file:
List<String> delPerfRecords = ReadFileContents(DelPerfFile);
. . .
private static List<String> ReadFileContents(string fileName)
{
List<String> fileContents = new List<string>();
try
{
fileContents = File.ReadAllLines(fileName).ToList();
}
catch (Exception ex)
{
RoboReporterConstsAndUtils.HandleException(ex);
}
return fileContents;
}
Then, writing to the file -- it marks the record/line in that file as having been processed, so that the same report is not re-generated the next time the file is examined:
MarkAsProcessed(DelPerfFile, qrRecord);
. . .
private static void MarkAsProcessed(string fileToUpdate, string
qrRecord)
{
try
{
var fileContents = File.ReadAllLines(fileToUpdate).ToList();
for (int i = 0; i < fileContents.Count; i++)
{
if (fileContents[i] == qrRecord)
{
fileContents[i] = string.Format("{0}{1} {2}"
qrRecord, RoboReporterConstsAndUtils.COMPLETED_FLAG, DateTime.Now);
}
}
// Will this automatically overwrite the existing?
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
}
catch (Exception ex)
{
RoboReporterConstsAndUtils.HandleException(ex);
}
}
So I do delete the file, but immediately replace it:
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
The files being read have contents such as this:
Opas,20170110,20161127,20161231-COMPLETED 1/10/2017 12:33:27 AM
Opas,20170209,20170101,20170128-COMPLETED 2/9/2017 11:26:04 AM
Opas,20170309,20170129,20170225-COMPLETED
Opas,20170409,20170226,20170401
If "-COMPLETED" appears at the end of the record/row/line, it is ignored - will not be processed.
Also, if the second element (at index 1) is a date in the future, it will not be processed (yet).
So, for these examples shown above, the first three have already been done, and will be subsequently ignored. The fourth one will not be acted on until on or after April 9th, 2017 (at which time the data within the data range of the last two dates will be retrieved).
Why is the file sometimes deleted? What can I do to prevent it from ever happening?
If helpful, in more context, the logic is like so:
internal static string GenerateAndSaveDelPerfReports()
{
string allUnitsProcessed = String.Empty;
bool success = false;
try
{
List<String> delPerfRecords = ReadFileContents(DelPerfFile);
List<QueuedReports> qrList = new List<QueuedReports>();
foreach (string qrRecord in delPerfRecords)
{
var qr = ConvertCRVRecordToQueuedReport(qrRecord);
// Rows that have already been processed return null
if (null == qr) continue;
// If the report has not yet been run, and it is due, add i
to the list
if (qr.DateToGenerate <= DateTime.Today)
{
var unit = qr.Unit;
qrList.Add(qr);
MarkAsProcessed(DelPerfFile, qrRecord);
if (String.IsNullOrWhiteSpace(allUnitsProcessed))
{
allUnitsProcessed = unit;
}
else if (!allUnitsProcessed.Contains(unit))
{
allUnitsProcessed = allUnitsProcessed + " and "
unit;
}
}
}
foreach (QueuedReports qrs in qrList)
{
GenerateAndSaveDelPerfReport(qrs);
success = true;
}
}
catch
{
success = false;
}
if (success)
{
return String.Format("Delivery Performance report[s] generate
for {0} by RoboReporter2017", allUnitsProcessed);
}
return String.Empty;
}
How can I ironclad this code to prevent the files from being periodically trashed?
UPDATE
I can't really test this, because the problem occurs so infrequently, but I wonder if adding a "pause" between the File.Delete() and the File.WriteAllLines() would solve the problem?
UPDATE 2
I'm not absolutely sure what the answer to my question is, so I won't add this as an answer, but my guess is that the File.Delete() and File.WriteAllLines() were occurring too close together and so the delete was sometimes occurring on both the old and the new copy of the file.
If so, a pause between the two calls may have solved the problem 99.42% of the time, but from what I found here, it seems the File.Delete() is redundant/superfluous anyway, and so I tested with the File.Delete() commented out, and it worked fine; so, I'm just doing without that occasionally problematic call now. I expect that to solve the issue.
// Will this automatically overwrite the existing?
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
I would simply add an extra parameter to WriteAllLines() (which could default to false) to tell the function to open the file in overwrite mode, and not call File.Delete() at all then.
Do you currently check the return value of the file open?
Update: ok, it looks like WriteAllLines() is a .Net Framework function and therefore cannot be changed, so I deleted this answer. However now this shows up in the comments, as a proposed solution on another forum:
"just use something like File.WriteAllText where if the file exists,
the data is just overwritten, if the file does not exist it will be
created."
And this was exactly what I meant (while thinking WriteAllLines() was a user defined function), because I've had similar problems in the past.
So, a solution like that could solve some tricky problems (instead of deleting/fast reopening, just overwriting the file) - also less work for the OS, and possibly less file/disk fragmentation.

Camera server died! Error 100 when starting recording

NOTICE: I'm Using Monodroid, expect C# code.
I'm facing this error when the _recorder.Start() is called.
CODE:
private void IniciarGrabacion()
{
try
{
CamcorderProfile camProfile = CamcordeProfile.Get(CamcorderQuality.High);
String outputFile = "/sdcard/trompiz.mp4";
_camera.Unlock ();
_recorder = new MediaRecorder();
_recorder.SetCamera(_camera);
_recorder.SetAudioSource(AudioSource.Default);
_recorder.SetVideoSource(VideoSource.Camera);
_recorder.SetProfile(camProfile);
_recorder.SetOutputFile(outputFile);
_recorder.SetPreviewDisplay(_preview.Holder.Surface);
_recorder.Prepare();
_recorder.Start(); // HERE IS WHERE THE ERROR APPEARS
}
catch(Exception ex)
{
string error = "Error starting Recording: " + ex.Message;
Log.Debug("ERROR",error);
Toast.MakeText(Application, error, ToastLength.Long).Show();
}
}
The outputFile is hardcoded because i'm still testing.
I can confirm that exists because it gets created.
I just figured the problem.
It wasn't on how the camera was handled.
It was the Profile setting.
CamcorderProfile camProfile = CamcordeProfile.Get(CamcorderQuality.High);
Might be a Device bug, but I cant set it to high. To make it work, I changed it to LOW.
CamcorderProfile camProfile = CamcordeProfile.Get(CamcorderQuality.Low);
I have a Zenithink C93 Z283 (H6_2f)
I hope this helps anyone else fighting with this...
Now I have to see how to record on High quality. I know I can because the native camera app records in high....

C# ArgumentOutOfRangeException when trying to retrieve data from a struct within an arraylist

Will try to post only relevant code as my program is quite large already. Basically the program adds customer information into an arraylist-struct. I've got the storing and saving and file loading working flawlessly, but when I'm trying to show the data I'm getting exceptions.
Most of the main code is on a class seperate to the forms, and this particular call comes from "frmViewRecords".
public void ViewData(int currentRecord)
{
string fn = ((custDetails)datalist[currentRecord]).firstName;
frmViewRecords viewRecords = new frmViewRecords();
viewRecords.WriteData(fn);
}
The above code is what causes the exception, but the code for the messagebox below works fine.
public void LoadData()
{
bool fileLoaded = false;
//Load the database
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); //Create the filestream
try
{
BinaryFormatter bf = new BinaryFormatter(); //New binary formatter for deserialization
datalist = (ArrayList)bf.Deserialize(fs);
fileLoaded = true; //Update the fileLoaded bool so that it doesn't open the file dialog instance
recordCount = datalist.Count;
MessageBox.Show("" + filename + " loaded successfully."); //Inform the user that the file was automatically loaded
MessageBox.Show("Test: " + ((custDetails)datalist[0]).firstName);
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename, "FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
if (MessageBox.Show("File isn't in the right location, this is normal if a dataset does not yet exist.\n\n If the file exists elsewhere click no and you will be prompted to find the database file, else click yes to create a default file.", "FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
fileLoaded = true;
CreateDefaultData();
}
}
I have tried 'string fn = ((custDetails)datalist[0]).firstName;' to ensure it isn't the variable causing the problems, and the exception still happens. I am pretty much out of ideas. The problem cannot be with struct or arraylist definition as the the messagebox in LoadData() works fine and outputs the correct information. I tried moving the messagebox to the ViewData method and that also began giving an exception so I can only assume something is wrong with my method?
These methods are on "MainClass.cs" and below is how I called the method from frmViewRecords:
MainClass mainClass = new MainClass();
int currentRecord = 0;
private void LoadData()
{
mainClass.ViewData(currentRecord);
}
It might be worth mentioning that previously, I was calling the data straight from frmViewRecords like so:
txtFirstName.Text = ((MainClass.custDetails)mainClass.datalist[currentRecord].firstName;
But after getting the same exception while the messagebox prompt worked, I rewrote it to the above and still I get the problem so I have no idea what is causing it.
There are no items in the datalist. Probably the value of the recordCount in the LoadData is zero as well. Try this:
if(datalist.Count != 0) { /* Get the current record */ }

Can't open a mpg-File for capture using EmguCV with C#

I'm trying to open a mpg-File using emguCV. I use the following code:
if (instance == null)
{
lock (m_lock)
{
try
{
instance = new Capture(0); // capture from camera works fine if a camera is connected
}
catch (NullReferenceException)
{
String sFileName = #"C:\tmp\MarkerMovie.mpg";
try
{
if (File.Exists(sFileName))
{
instance = new Capture(sFileName); // here the exception is thrown
}
else
{
MessageBox.Show("No Camera and no Video-File found");
}
}
catch (NullReferenceException)
{
MessageBox.Show("Couldn't open Video: "+sFileName);
}
}
}
}
If a webcam is connected everything works fine, but when I unplug the webcam the line instance = new Capture(sFileName); throws a NullReferenceException:
Message = "Unable to create capture from C:\tmp\MarkerMovie.mpg"
I debugged and found the reason is in the constructor of capture. The following command always returns a Null-Pointer:
_ptr = CvInvoke.cvCreateFileCapture(fileName);
I could open the same video using C++ using this code:
cap = cvCaptureFromFile("C:\\tmp\\MarkerMovie.mpg");
I'm new to openCV, so I'm not sure which information you need to help me. I installed emguCV yesterday from http://sourceforge.net/projects/emgucv/ on a Windows XP computer. The installer-version is x86_2.3.0.1416. I included opencv_core231.dll, opencv_highgui231.dll and opencv_imgproc231.dll to my project.
Does somebody know how I can make this code working?
Let me know if you need more information.
Thanks.
I had the same problem and adding the opencv_ffmpeg.dll to the project seems to solve it. (Found in the bin directory in the Emgu CV directory) I have tried it on the project that you posted and it seems to be working too. Hope it helps.
With EmguCV in C#, you need to put the opencv_ffmpeg.dll, for example: opencv_ffmpeg2410.dll, be careful if you have x86 or 64 bits

C# dynamic type / Silverlight 4 AutomationFactory question

I have this little function in my Silverlight 4 OOB app that gets an image from a scanner:
public static BitmapImage GetImageFromScanner()
{
try
{
using (dynamic CommonDialog = AutomationFactory.CreateObject("WIA.CommonDialog"))
{
//Param meanings: (scanner, black and white, maximize quality)
dynamic imageFile = CommonDialog.ShowAcquireImage(1, 2, 131072);
if (imageFile != null)
{
return (BitmapImage)imageFile;
}
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
if (ex.ErrorCode == -2145320939)
{
MessageBox.Show("Could not find an attached scanner.", "Scanner Error", MessageBoxButton.OK);
}
else if (ex.ErrorCode == -2145320957)
{
MessageBox.Show("There is no paper in the scanner.", "Scanner Error", MessageBoxButton.OK);
}
}
return null;
}
I'd like the function to return a BitmapImage but I'm not sure how to cast the dynamic type. I'm not even sure what type imageFile would be if it weren't dynamic. The above method returns the following exception:
Unable to cast object of type 'System.Runtime.InteropServices.Automation.AutomationMetaObjectProvider' to type 'System.Windows.Media.Imaging.BitmapImage'.
Can someone provide guidance? I'm not sure if this is a question about the dynamic keyword or AutomationFactory since both are new to me. :/
EDIT:
I know it is an image because if I do this:
string filePath = string.Format("c:\\{0}.jpg", Guid.NewGuid());
imageFile.SaveFile(filePath);
MessageBox.Show(string.Format("Saved {0}", filePath));
It saves the document scanned as a jpg. I tried to figure out what object in the .NET framework have a SaveFile() method and there are seemingly many.
See if this helps: Scanning an Image from Silverlight 4 using WIA Automation
It doesn't seem to be straightforward to get an image...
ShowAcquireImage returns ImageFile, it have methods to save content to disk or stream

Categories

Resources