ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • String -> 모스(morse)부호 sound출력 -> 녹음(recoding) -> String
    IT/java 2021. 2. 4. 15:37

    안녕하세욤^^ visualkhh입니다.

    1년전쯤에 심심해서 만들어본

    모스부호 사운드 출력 ->  녹음 -> 복호화 입니다.

    String ->  모스(morse)부호 sound출력  ->  녹음(recoding) -> String




    출력

    https://github.com/visualkhh/javautil-visualkhh/blob/master/Morse/src/Morse.java

    녹음

    https://github.com/visualkhh/javautil-visualkhh/blob/master/Morse/src/SountRecord.java




    
    
    public class Morse {
    
    
    	
    	
    	HashMap<String, String> em = null;
    	HashMap<String, String> me = null;
    	
        String[] alpha = { 
        		"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
                "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
                "u", "v", "w", "x", "y", "z", "1", "2", "3", "4",
                "5", "6", "7", "8", "9", "0", " " 
                };
        String[] morse = {
        		".-",		"-...",		"-.-.", 	"-..", 		".", 		"..-.",		"--.",		"....",		"..",		".---",
        		"-.-",		".-..",		"--", 		"-.", 		"---",		".--.",		"--.-",		".-.",		"...",		"-",
        		"..-", 		"...-", 	".--", 		"-..-",		"-.--",		"--..",		".----",	"..---",	"...--",	"....-",
        		".....",	"-....", 	"--...", 	"---..",	"----.",	"-----",	"|" };
    //	
    	public Morse() {
    		em = new HashMap<String, String>();
    		me = new HashMap<String, String>();
    		for (int i = 0; i < alpha.length; i++) {
    			em.put(alpha[i], morse[i]);
    			me.put(morse[i], alpha[i]);
    		}
    	}
        
        
    	public String toMorse(String engStr){
    		String engStru = engStr.toLowerCase();
    		StringBuffer b = new StringBuffer();
    		for (int i = 0; i < engStru.length(); i++) {
    			b.append(em.get(engStru.substring(i, i+1)));
    			if(i+1 < engStru.length()){
    				b.append("|");
    			}
    		}
    		return b.toString();
    	}
    
    	public String toEnglish(String morseStr){
    		StringBuffer b = new StringBuffer();
    		String[] morseArr = morseStr.split("\\|");
    		for (int i = 0; i < morseArr.length; i++) {
    			b.append(me.get(morseArr[i]));
    		}
    		return b.toString();
    	}
    	
    	
    	public String toMorseBybyte(File file) throws IOException{
    		InputStream input = new FileInputStream(file);
    		byte[] buf = new byte[(int)file.length()];
    		input.read(buf);
    		input.close();
    		return toMorseBybyte(buf);
    	}
    	public String toMorseBybyte(byte[] byteArr){
    		StringBuffer b = new StringBuffer();
    		for (int i = 0; i < byteArr.length; i++) {
    			b.append(String.format("%X ", byteArr[i]));
    		}
    //		return b.toString();
    		return toMorse(b.toString());
    	}
    	public byte[] morseToByteArray(String morseStr){
    		int dcnt	= StringUtil.getMatchingCount("\\.", morseStr);
    		int ecnt	= StringUtil.getMatchingCount("\\|", morseStr);
    		int lcnt	= StringUtil.getMatchingCount("-", morseStr);
    		int cnt 	= morseStr.length();
    		int hs		= 1000; //10000 / 1 초
    		int sc		= (dcnt*hs) + (ecnt*hs*3) + (cnt*hs) + (lcnt*(hs*2));
    		
    		byte[] pcm_data = new byte[sc];
    		double L1 = 44100.0/240.0;
    		double L2 = 44100.0/240.0;
    		  
    		  //System.out.println(sc+" "+" "+pcm_data.length+"  "+dcnt+" "+ecnt+" "+lcnt+" " );
    		  int startIndex=0;
    		  for (int i = 0; i < morseStr.length(); i++) {
    			  String s = morseStr.substring(i, i+1);
    			  int width = s.equals("-") ? hs*2 : hs;
    			  //System.out.println(width);
    			  
    			  for(int j = startIndex; j < startIndex + width; j++) {
    				  //System.out.println(j);
    				  if(s.equals(".") || s.equals("-")){
    					  pcm_data[j] = (byte)(1000 * Math.sin((j/L1) * Math.PI * 2));
    					  //System.out.println((byte)pcm_data[j]);
    					  //pcm_data[j]=(byte) 225;//(byte)0xff;
    					  //pcm_data[j] += (byte)(100*Math.sin((j/L2)*Math.PI*2));
    					  //pcm_data[j] = (byte) (1024 * Math.cos((double)Math.PI *L1)* Math.sin(Math.PI * sc)*100);
    				  }else{
    					  break;
    				  }
    			  }
    			  
    			  startIndex += width;
    			  startIndex += s.equals("|") ? hs*3 : hs;
    //			  startIndex +=hs*2;
    		  }
    		  
    		  return pcm_data;
    	}
    	//신호간격은1타점,   문자간격은 3타점 , 단어간격은 7타점,  공백은 허용하지않아요
    	public void writeWAV(String morseStr, File file){
    		byte[] pcm_data = morseToByteArray(morseStr);
    		AudioFormat frmt = getAudioFormat();
    		AudioInputStream ais = new AudioInputStream(
    		    new ByteArrayInputStream(pcm_data), frmt, pcm_data.length / frmt.getFrameSize()
    		  );
    		 
    		  try {
    		    AudioSystem.write(ais, AudioFileFormat.Type.WAVE, file);
    		  } 
    		  catch(Exception e) {
    		    e.printStackTrace();
    		  }
    	}
    	
    	public AudioFormat getAudioFormat(){
    		int sampleRate = 44100;
    		int sampleSizeInBits = 8;
    		int channeles = 1;
    		boolean signed = true;
    		boolean bigEndian = true;
    		return new AudioFormat(sampleRate, sampleSizeInBits, channeles, signed, bigEndian);	
    	}
    	
    	
    	public void outSound(String morseStr) throws LineUnavailableException {
    		byte[] pcm_data = morseToByteArray(morseStr);
    		
    		AudioFormat format = getAudioFormat();
    		DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
    		SourceDataLine line = null;
    		line = (SourceDataLine) AudioSystem.getLine(info);
    		line.open(format);
    		line.start();
    		line.write(pcm_data, 0, pcm_data.length);
    		line.drain();
    		line.close();
    	}
    	
    	
    	public static void main(String[] args) throws Exception {
    		Morse m = new Morse();
    		
    		String msg = m.toMorse("goodjobman");
    		System.out.println(msg);
    		
    		m.outSound(msg);
    		
    		msg = m.toEnglish("...-|..|...|..-|.-|.-..|-.-|....|....");
    		System.out.println(msg);
    		
    		
    
    //		m.writeWAV(a,new File("c:\\test.wav"));
    	}
    
    }




    
    public class SountRecord {
    
    	ArrayList<MorseRecordDTO> list = new ArrayList<MorseRecordDTO>();
    	TargetDataLine line = null;
    	AudioInputStream ais = null;
    	int nRead = 0;
    	public SountRecord() {
    		// TODO Auto-generated constructor stub
    	}
    	LogK log = LogK.getInstance();
    	public AudioFormat getAudioFormat(){
    		int sampleRate = 44100;
    		int sampleSizeInBits = 8;
    		int channeles = 1;
    		boolean signed = true;
    		boolean bigEndian = true;
    		return new AudioFormat(sampleRate, sampleSizeInBits, channeles, signed, bigEndian);	
    	}
    	public void start() throws LineUnavailableException, IOException{
    		AudioFormat format = getAudioFormat();
    		DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    		line = (TargetDataLine)AudioSystem.getLine(info);
    		line.open(format);
    		System.out.println("-st--");
    		line.start();
    		
    		System.out.println("---0");
    		ais = new AudioInputStream(line);
    
    		
    		
    		nRead=0;
    		byte[] abData	= new byte[100];
    		int blockCnt	= 0;
    		
    		while(nRead!=-1){
    			nRead = ais.read(abData, 0, abData.length);
    			if(nRead >=0 ){
    				log.debug("msg", abData);
    				//logic
    				int scopeCnt=0;
    				for (int j=0; j<nRead; j++){
    					if( (abData[j]&0xFF) >(5) && (abData[j]&0xFF)<250 ){
    						scopeCnt++;
    					}
    				}
    				log.debug("blockCnt:"+blockCnt+"  scopeCnt:"+scopeCnt);
    				
    				//처음
    				boolean isDot = scopeCnt > abData.length/2;
    				if(isDot && list.size()==0){
    					log.debug("start");
    					list.add(new MorseRecordDTO(".",1));
    				}
    				//닷나올때
    				else if(isDot && list.size()>0){
    					MorseRecordDTO mr = list.get(list.size()-1);
    					if(mr.getMsg().equals(" ")){
    						list.add(new MorseRecordDTO(".", 1));
    					}else{
    						mr.setLength(mr.getLength()+1);
    					}
    				}
    				//아닐때
    				else if(!isDot && list.size()>0){
    					MorseRecordDTO mr = list.get(list.size()-1);
    					if(mr.getMsg().equals(".")){
    						list.add(new MorseRecordDTO(" ", 1));
    					}else{
    						mr.setLength(mr.getLength()+1);
    					}
    				}
    				
    			}
    			//break;
    		}
    		
    		
    //		System.out.println("---1");
    //		AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("c:/rr.wav"));
    //		System.out.println("---0");
    		
    //		try {
    //			Thread.sleep(5000);
    //		} catch (InterruptedException e) {
    //			// TODO Auto-generated catch block
    //			e.printStackTrace();
    //		}
    		
    		
    	}
    	public void finish(){
    		nRead=-1;
    		try {
    			Thread.sleep(5000);
    			ais.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		line.stop();
    		line.close();
    		
    		
    		int dMin	= Integer.MAX_VALUE;
    		int dMax	= Integer.MIN_VALUE;
    		int sMin	= Integer.MAX_VALUE;
    		int sMax	= Integer.MIN_VALUE;
    		for (int i = 0; i < list.size()-1; i++) {
    			MorseRecordDTO mr = list.get(i);
    			if(mr.getMsg().equals(".")){
    				dMin = Math.min(dMin, mr.getLength());
    				dMax = Math.max(dMax, mr.getLength());
    			}else if(mr.getMsg().equals(" ")){
    				sMin = Math.min(sMin, mr.getLength());
    				sMax = Math.max(sMax, mr.getLength());
    			}
    		}
    		int dscop	= dMin+   ((dMax-dMin)/2);	
    		int sscop	= sMin+   ((sMax-sMin)/2);	
    		
    		
    		log.debug("dMin("+dMin+") dMax("+dMax+") sMin("+sMin+")  sMax("+sMax+")     // dscop("+dscop+")  sscop("+sscop+")");
    		
    		String msg = "";
    		for (int i = 0; i < list.size()-1; i++){
    			MorseRecordDTO mr = list.get(i);
    			log.debug("result("+i+")"+mr.getMsg()+"  "+mr.getLength()+"   ->"+dscop+", "+sscop);
    			if(mr.getMsg().equals(".")){
    				if(mr.getLength()>dscop){
    					msg+="-";
    				}else{
    					msg+=".";
    				}
    			}else if(mr.getMsg().equals(" ")){
    				if(mr.getLength()>sscop){
    					msg+=" ";
    				}else{
    					msg+="";
    				}
    			}
    		}
    		log.debug("==end==");
    		log.debug(msg);
    		log.debug(new Morse().toEnglish(msg.replace(" ", "|")));
    	}
    	public static void main(String[] args) throws Exception {
    		
    		final SountRecord s = new SountRecord();
    		
    		Thread stopper = new Thread(new Runnable() {
    			public void run() {
    				Scanner input = new Scanner(System.in);
    				String ans = input.nextLine();
    				s.finish();
    				System.exit(0);
    			}
    		});
    //
    		stopper.start();
    		s.start();
    	}
    }




    보안프로그램도 소리를 막을순 없겠죠??

    visualkhh@gmail.com

    좋은하루되세요.

    'IT > java' 카테고리의 다른 글

    페이징(Paging) 계산 Class  (0) 2021.02.04
    심심해서 만들어본 Object in Class, parameter path 접근 Finder  (0) 2021.02.04

    댓글

Designed by Tistory.