Add support for txt format

This commit is contained in:
hhhzzzsss 2024-05-23 13:12:19 -05:00
parent 29b36ea4b6
commit 9b961dfabf
2 changed files with 48 additions and 0 deletions

View file

@ -0,0 +1,40 @@
package com.github.hhhzzzsss.songplayer.conversion;
import com.github.hhhzzzsss.songplayer.song.Note;
import com.github.hhhzzzsss.songplayer.song.Song;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class TxtConverter {
public static Song getSongFromBytes(byte[] bytes, String fileName) throws IOException {
Song song = new Song(fileName);
String strContent = new String(bytes, StandardCharsets.UTF_8);
String[] lines = strContent.split("\\r?\\n");
for (int lineNum = 1; lineNum <= lines.length; lineNum++) {
String line = lines[lineNum-1].strip();
if (line.startsWith("#")) continue;
String[] split = line.split(":");
if (split.length != 3) throw new IOException("Invalid format at line " + lineNum);
int tick, pitch, instrument;
try {
tick = Integer.parseInt(split[0]);
pitch = Integer.parseInt(split[1]);
instrument = Integer.parseInt(split[2]);
} catch (NumberFormatException e) {
throw new IOException("Invalid format at line " + lineNum);
}
int noteId = pitch + instrument*25;
song.add(new Note(noteId, tick*50));
song.length = song.get(song.size()-1).time + 50;
}
song.sort();
return song;
}
}

View file

@ -4,6 +4,7 @@ import com.github.hhhzzzsss.songplayer.SongPlayer;
import com.github.hhhzzzsss.songplayer.Util; import com.github.hhhzzzsss.songplayer.Util;
import com.github.hhhzzzsss.songplayer.conversion.MidiConverter; import com.github.hhhzzzsss.songplayer.conversion.MidiConverter;
import com.github.hhhzzzsss.songplayer.conversion.NBSConverter; import com.github.hhhzzzsss.songplayer.conversion.NBSConverter;
import com.github.hhhzzzsss.songplayer.conversion.TxtConverter;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
@ -75,6 +76,13 @@ public class SongLoaderThread extends Thread{
catch (Exception e) {} catch (Exception e) {}
} }
if (song == null) {
try {
song = TxtConverter.getSongFromBytes(bytes, filename);
}
catch (Exception e) {}
}
if (song == null) { if (song == null) {
throw new IOException("Invalid song format"); throw new IOException("Invalid song format");
} }