diff --git a/src/main/java/com/github/hhhzzzsss/songplayer/conversion/TxtConverter.java b/src/main/java/com/github/hhhzzzsss/songplayer/conversion/TxtConverter.java new file mode 100644 index 0000000..2257e67 --- /dev/null +++ b/src/main/java/com/github/hhhzzzsss/songplayer/conversion/TxtConverter.java @@ -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; + } +} diff --git a/src/main/java/com/github/hhhzzzsss/songplayer/song/SongLoaderThread.java b/src/main/java/com/github/hhhzzzsss/songplayer/song/SongLoaderThread.java index cc89583..7717d84 100644 --- a/src/main/java/com/github/hhhzzzsss/songplayer/song/SongLoaderThread.java +++ b/src/main/java/com/github/hhhzzzsss/songplayer/song/SongLoaderThread.java @@ -4,6 +4,7 @@ import com.github.hhhzzzsss.songplayer.SongPlayer; import com.github.hhhzzzsss.songplayer.Util; import com.github.hhhzzzsss.songplayer.conversion.MidiConverter; import com.github.hhhzzzsss.songplayer.conversion.NBSConverter; +import com.github.hhhzzzsss.songplayer.conversion.TxtConverter; import java.io.IOException; import java.net.URL; @@ -75,6 +76,13 @@ public class SongLoaderThread extends Thread{ catch (Exception e) {} } + if (song == null) { + try { + song = TxtConverter.getSongFromBytes(bytes, filename); + } + catch (Exception e) {} + } + if (song == null) { throw new IOException("Invalid song format"); }