Last active
July 17, 2019 13:31
-
-
Save Xyene/6478305 to your computer and use it in GitHub Desktop.
Possibly the most concise String -> Morse code converter / player possible in Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jmorse; | |
import java.io.*; | |
import java.util.*; | |
import javax.sound.sampled.*; | |
public class Morse { | |
private static final int DOT = 200, DASH = DOT * 3, FREQ = 800; | |
private static String[] morse = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; | |
public static void main(String[] args) throws IOException, LineUnavailableException, InterruptedException { | |
boolean sound = !Arrays.asList(args).contains("-n"); | |
System.out.print("Hit enter to begin transmission."); | |
String line; | |
while ((line = new BufferedReader(new InputStreamReader(System.in)).readLine()) != null) { | |
for (char c : line.toUpperCase().toCharArray()) { | |
for (char note : (Character.isLetterOrDigit(c) ? morse[c - 'A'].toCharArray() : new char[]{'\n'})) { | |
System.out.print(note == ' ' ? "\n" : note); | |
if (sound) { | |
try (SourceDataLine sdl = AudioSystem.getSourceDataLine(new AudioFormat(8000F, 8, 1, true, false))) { | |
sdl.open(sdl.getFormat()); | |
sdl.start(); | |
for (int i = 0; i < (note == '.' ? DOT : DASH) * 8; i++) { | |
sdl.write(new byte[]{(byte) (Math.sin(i / (8000F / FREQ) * 2.0 * Math.PI) * 127.0)}, 0, 1); | |
} | |
sdl.drain(); | |
} | |
} | |
Thread.sleep(DOT / 5); | |
} | |
} | |
System.out.print("\n\n>>> "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, some solution to get reverse, I mean to get morse code from audio? thanks