MusicBoxConverter/MusicBoxConverter/MusicBoxScoreGenerator.cs

73 lines
1.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Melanchall.DryWetMidi.Smf;
using Melanchall.DryWetMidi.Smf.Interaction;
using SBRL.Utilities;
namespace MusicBoxConverter
{
public class MusicBoxScoreGenerator
{
public Vector2 offset { get; set; } = new Vector2(10, 10);
public Vector2 scaleFactor { get; set; } = new Vector2(0.1f, 4f);
public int holeSize { get; set; } = 5;
private int trackLength;
public int TrackLength {
get {
if(trackLength == null)
trackLength = (int)AllNotes().Max((Note arg) => arg.Time);
return trackLength;
}
}
MidiFile midiFile;
public MusicBoxScoreGenerator(string filename)
{
midiFile = MidiFile.Read("/home/sbrl/Music/Sheets/HappyBirthday.midi");
}
public void Output(string destinationFilename)
{
SvgWriter svg = new SvgWriter(destinationFilename);
svg.WriteRectangle(offset, new Vector2(TrackLength, 128).Multiply(scaleFactor));
for(int i = 0; i < 255; i += 5)
{
Vector2 start = offset.Add(new Vector2(0, i));
svg.WriteLine(start, start.Add(new Vector2(TrackLength, 0)));
}
foreach(Note note in AllNotes())
{
Console.WriteLine("[{0}] {1}/{2}", note.Time, note.NoteName, note.NoteNumber);
svg.WriteCircle(
new Vector2(
offset.X + note.Time * scaleFactor.X,
offset.Y + note.NoteNumber * scaleFactor.Y
),
holeSize // radius
);
}
svg.Complete();
}
public IEnumerable<Note> AllNotes()
{
foreach(TrackChunk chunk in midiFile.Chunks.OfType<TrackChunk>())
{
using(NotesManager notesManager = new NotesManager(chunk.Events))
{
foreach(Note note in notesManager.Notes)
yield return note;
}
}
}
}
}