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>>> "); | |
} | |
} | |
} |
Hello, some solution to get reverse, I mean to get morse code from audio? thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know this is two years old but I like the code for the fact that it is so simple and compact. I just have one question..... How do you speed up and or slow down the playback without jeopardizing the sound of the beep?"