How to get real time of a midi event - c#

I am reading a midi file with this parser.
But I cannot read the real time.
MidiFile midiFile = new MidiFile("/Jenkins.mid");
var ticksPerQuarterNote = _midiFile.TicksPerQuarterNote;
foreach (MidiTrack track in midiFile.Tracks)
{
foreach (MidiEvent midiEvent in track.MidiEvents)
{
if (midiEvent.MidiEventType != MidiEventType.NoteOn)
continue;
int note = midiEvent.Note;
int time = midiEvent.Time;
}
}
All the formulas I have seen on the internet use the tempo, but I can't find it.

You can use my DryWetMIDI library which does all these calculations for you:
var midiFile = MidiFile.Read("Jenkins.mid");
var tempoMap = midiFile.GetTempoMap();
foreach (var trackChunk in midiFile.GetTrackChunks())
{
foreach (var timedEvent in trackChunk.GetTimedEvents())
{
if (timedEvent.Event.MidiEventType != MidiEventType.NoteOn)
continue;
MetricTimeSpan metricTime = timedEvent.TimeAs<MetricTimeSpan>(tempoMap);
}
}
Here we get metric time (hours/minutes/seconds/ms), but the library provides several other formats you can convert MIDI time to. Please read the article of the library docs to learn more: Time and length.
More than that if you actually want to get notes instead of events, it's super easy with DryWetMIDI:
var notes = midiFile.GetNotes();
You can also use TimeAs method on notes.

Related

How to read data from RFIDControllerMfrc522

I'm trying to find substitution for my rfid card. The current script is made in Python and is using SimpleMFRC522 library which is working perfectly. However, I want to use C#.
I found one library Unosquare.RaspberryIO.Peripherals, but I can't find good documentation. The function below is returning data 4, which is not the data that is written on the card.
If there is any other good RFID library, let me know. Thank you in advance!
Pi.Init<BootstrapWiringPi>();
var _reader = new RFIDControllerMfrc522();
while (true)
{
if (_reader.DetectCard() == RFIDControllerMfrc522.Status.AllOk)
{
var uidResponse = _reader.ReadCardUniqueId();
if (uidResponse.Status == RFIDControllerMfrc522.Status.AllOk)
{
var cardUid = uidResponse.Data;
_reader.SelectCardUniqueId(cardUid);
try
{
if (_reader.AuthenticateCard1A(cardUid, 7) == RFIDControllerMfrc522.Status.AllOk)
{
var a = _reader.CardReadData(0);
foreach (var item in a.Data)
{
Console.WriteLine(item);
}
}
}
finally
{
_reader.ClearCardSelection();
}
}
}
}

Unity crashes when reading a large csv file

I need to find a way to read information out of a very big CSV file with unity. The file is approx. 15000*4000 entries with almost 200MB and could even be longer.
Just using ReadAllLines on the file does kind of work but as soon as I try to do any operation on it, it will crash. Here is the code I am using just counting all non zero values which already crashes it. It's okay if the code might need loading time but it shouldn't crash. I assume it's because I save everything in the memory and therefore flood my RAM? Any ideas how to fix this that it won't crash?
private void readCSV()
{
string[] lines = File.ReadAllLines("Assets/Datasets/testCsv.csv");
foreach (string line in lines)
{
List<string> values = new List<string>();
values = line.Split(',').ToList();
int i = 0;
foreach (string val in values)
{
if (val != "0")
{
i++;
}
}
}
}
As I already stated in your other question you should rather go with a streamed solution in order to not load the entire thing into memory at all.
Also both FileIO as well as string.Split are slow especially for soany entries! Rather use a background thread / async Task for this!
The next future possible issue in your case 15000*4000 entries means a total of 60000000 cells. Which is still fine. However, the maximum value of int is 2147483647 so if your file grows further it might break / behave unexpected => rather use e.g. uint or directly ulong to avoid that issue.
private async Task<ulong> CountNonZeroEntries()
{
ulong count = 0;
// Using a stream reader you can load the content into memory one line at a time
using(var sr = new StreamReader("Assets/Datasets/testCsv.csv"))
{
while(true)
{
var line = await sr.ReadLineAsync();
if(line == null) break;
var values = line.Split(',');
foreach(var v in values)
{
if(v != "0") count++;
}
}
}
return count;
}
And then of course you would need to wait for the result e.g. using
// If you declare Start as asnyc Unity automatically calls it asynchronously
private async void Start()
{
var count = await CountNonZeroEntries();
Debug.Log($"{count} cells are != \"0\".");
}
The same can be done using Linq a bit easier to write in my eyes
using System.Linq;
...
private Task<ulong> CountNonZeroEntries()
{
return File.ReadLines("Assets/Datasets/testCsv.csv").Select(line => line.Split(',')).Count(v => v != "0");
}
Also File.ReadLines doesn't load the entire content at once but rather a lazy enumerable so you can use Linq queries on them one by one.

Get all Youtube videos in a Youtube Playlist including the duration of it

So I need to get the duration of each Video in a Playlist, the problem is that there is no duration included, theoretically I could calculate it with the EndAt and StartAt values but they are no longer filled with data and always will be null (see documentation).
So all of this is done so far with the Google.Apis.YouTube.v3. The code I currently have:
var PlaylistItemRequest = YouTubeService.PlaylistItems.List("snippet,contentDetails");
PlaylistItemRequest.PlaylistId = Find;
PlaylistItemRequest.MaxResults = 50;
List<Song> PlaylistItems = new List<Song>();
while (true)
{
var PlaylistItemResponse = await PlaylistItemRequest.ExecuteAsync();
foreach (var playlistitem in PlaylistItemResponse.Items)
PlaylistItems.Add(new Song(playlistitem.Snippet.Title, playlistitem.ContentDetails.EndAt, playlistitem.ContentDetails.StartAt, $"https://www.youtube.com/watch?v={playlistitem.Id}", playlistitem.Snippet.Thumbnails.Default__.Url, DateTime.UtcNow, null, user.Id));
if (PlaylistItemResponse.NextPageToken == null) break;
PlaylistItemRequest.PageToken = PlaylistItemResponse.NextPageToken;
}
Then I thought I could just do something like that, because this would give me the duration of the video:
var request = YouTubeService.Videos.List("snippet,contentDetails,statistics");
The problem is that I would need to send this for each song in the playlist and I do not want to risk to break the Google API ratelimits. Since 200 requests are a lot.
Any help is appreciated!
Note: I would need a solution with no manual delay if possible.

Multithreading with Windows Store Applications

We are currently creating a Windows Store Application which gains information from an RSS feed and inputs this information into an ObservableCollection. The issue we are having is when the information is being gained, the Applications UI becomes unresponsive.
In order to get around this, I thought about creating a new thread and calling the method within this. Though, after some research we realised that this was no longer possible in Windows Store Apps. How can we get around this?
The method that collects the information is below.
public void getFeed()
{
setupImages();
string[] feedUrls = new string[] {
"http://www.igadgetos.co.uk/blog/category/gadget-news/feed/",
"http://www.igadgetos.co.uk/blog/category/gadget-reviews/feed/",
"http://www.igadgetos.co.uk/blog/category/videos/feed/",
"http://www.igadgetos.co.uk/blog/category/gaming/feed/",
"http://www.igadgetos.co.uk/blog/category/jailbreak-2/feed/",
"http://www.igadgetos.co.uk/blog/category/kickstarter/feed/",
"http://www.igadgetos.co.uk/blog/category/cars-2/feed/",
"http://www.igadgetos.co.uk/blog/category/software/feed/",
"http://www.igadgetos.co.uk/blog/category/updates/feed/"
};
{
try
{
XNamespace dc = "http://purl.org/dc/elements/1.1/";
XNamespace content = "http://purl.org/rss/1.0/modules/content/";
foreach (var feedUrl in feedUrls)
{
var doc = XDocument.Load(feedUrl);
var feed = doc.Descendants("item").Select(c => new ArticleItem() //Creates a copy of the ArticleItem Class.
{
Title = c.Element("title").Value,
//There are another 4 of these.
Post = stripTags(c.Element(content + "encoded").Value) }
).OrderByDescending(c => c.PubDate);
this.moveItems = feed.ToList();
foreach (var item in moveItems)
{
item.ID = feedItems.Count;
feedItems.Add(item);
}
}
lastUpdated = DateTime.Now;
}
catch
{
MessageDialog popup = new MessageDialog("An error has occured downloading the feed, please try again later.");
popup.Commands.Add(new UICommand("Okay"));
popup.Title = "ERROR";
popup.ShowAsync();
}
}
}
How would we be able to cause the Application to not freeze as we gain this information, as Threading is not possible within Windows Store Applications.
E.g - We planned to use;
Thread newThread = new Thread(getFeed);
newThread.Start
You need to use the well documented async pattern for your operations that happen on the UI thread. The link given by Paul-Jan in the comments is where you need to start. http://msdn.microsoft.com/en-us/library/windows/apps/hh994635.aspx

Examples of Quickbase API in C#

I am fairly new to the use of APIs and haven't touched Quickbase until today. I was researching the Quickbase API and it seemed as if all the examples I saw were written in XML or some similar variant. Is there a way to write code in C# that will do the same things that I saw could be done on the Quickbase website's API documentation? If you know of any code examples, please let me know.
There is a QuickBase C# SDK that might help get you started.
using System;
using Intuit.QuickBase.Client;
namespace MyProgram.QB.Interaction
{
class MyApplication
{
static void Main(string[] args)
{
var client = QuickBase.Client.QuickBase.Login("your_QB_username", "your_QB_password");
var application = client.Connect("your_app_dbid", "your_app_token");
var table = application.GetTable("your_table_dbid");
table.Query();
foreach(var record in table.Records)
{
Console.WriteLine(record["your_column_heading"]);
}
client.Logout();
}
}
}
There is also a QuickBase API Wrapper example as well.
Back in 2009 I wrote an .NET API for QuickBase which makes working with the platform easy, it also supports uploading and downloading of attached files.
IQuickBaseService svc = new QuickBaseService("user", "pass", "URL", "token");
Schema schema = svc.GetSchema("DBID");
Console.WriteLine("Schema : {0}", schema.Name);
Console.WriteLine("Variables - ");
for (KeyValuePair<string, string> ent in schema.Variables.OrderBy(en => en.Key)) {
Console.WriteLine("Var: {0} = {1}", ent.Key, ent.Value);
}
for (Query q : schema.Queries) {
// Work with queries.
}
// schema.Children
// schema.Fields
// ...
svc.SignOut();
Performing a query is simple.
QueryResult res;
res = svc.Query("tableid", 1); // Execute query number 1
res = svc.Query("tableid", "{{140.EX.'1'}}") // execute QB query text
foreach (QueryRow row in result.Rows) {
// Do something with row, use get<type>, not all shown here.
// row.GetBool(1);
// row.GetInt(1);
// row.GetLong(1);
// row.GetFloat(1);
// row.GetDouble(1);
// row.GetDecimal(1);
// row.GetString(1);
// row.GetDate(1);
// row.GetDateTime(1);
// row.GetObject(1);
}
QuickBase SDK Code is now moved to github https://github.com/QuickbaseAdmirer/QuickBase-C-Sharp-SDK

Categories

Resources