|
本帖最后由 cloudor 于 2011-7-24 10:01 编辑
为了让声音传感器识别多种指令。我把声音按照长短音的序列识别出来,这样就能够用嘴巴发出“滴滴~滴"的电报码来对NXT发出多种语音指令控制。
其中main方法就是使用例子。
比如,
发的是三个短音,收到的cmd就是“...”;
发的是两个长音,收到的cmd就是"--"。
电报码调试
import java.util.ArrayList;
import java.util.List;
import lejos.nxt.Button;
import lejos.nxt.SensorPort;
import lejos.nxt.SensorPortListener;
import lejos.nxt.Sound;
import lejos.nxt.SoundSensor;
import lejos.nxt.comm.RConsole;
/**
* @author PuYun <cloudor@gmail.com>
* @version $Id$
*
*/
public class BeepInput implements SensorPortListener, Runnable
{
public static interface Listener
{
void beeps(String cmd);
}
public static void main(String[] args)
{
Sound.beep();
RConsole.open();
BeepInput input = new BeepInput(SensorPort.S1);
input.addListener(new Listener()
{
public void beeps(String cmd)
{
System.out.println(cmd);
}
});
Button.waitForPress();
Sound.beepSequence();
RConsole.close();
}
private int beepCommandInterval;
private String beepsCache = "";
private long lastBeep;
private List<Listener> listenerList = new ArrayList<Listener>();
private Object lock = new Object();
private int longBeepTime;
private Thread monitor;
private volatile long noiseEnd;
private long noiseStart;
private int shortBeepTime;
private SoundSensor sound;
public BeepInput(SensorPort port)
{
this(port, 50, 400, 1000);
}
public BeepInput(SensorPort port, int shortBeepTime, int longBeepTime,
int beepCommandInterval)
{
this.sound = new SoundSensor(port, true);
this.shortBeepTime = shortBeepTime;
this.longBeepTime = longBeepTime;
this.beepCommandInterval = beepCommandInterval;
port.addSensorPortListener(this);
monitor = new Thread(this, "BeepMonitor");
monitor.setDaemon(true);
monitor.start();
}
public void addListener(Listener l)
{
listenerList.add(l);
}
public void removeListener(Listener l)
{
listenerList.remove(l);
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run()
{
while (true)
{
Thread.yield();
if (sound.readValue() > 3)
{
continue;
}
long current = System.currentTimeMillis();
if (noiseEnd > 0)
{
boolean quietForAWhile = false;
synchronized (lock)
{
quietForAWhile = noiseEnd > 0 && current - noiseEnd > 20;
}
if (quietForAWhile)
{
long time = noiseEnd - noiseStart;
if (time > longBeepTime)
{
beepsCache += "-";
lastBeep = current;
} else if (time > shortBeepTime)
{
beepsCache += ".";
lastBeep = current;
}
synchronized (lock)
{
noiseStart = -1;
noiseEnd = -1;
}
}
} else if (lastBeep > 0 && current - lastBeep > beepCommandInterval)
{
for (Listener l : listenerList)
{
l.beeps(beepsCache);
}
lastBeep = 0;
beepsCache = "";
}
}
}
/*
* (non-Javadoc)
*
* @see lejos.nxt.SensorPortListener#stateChanged(lejos.nxt.SensorPort, int, int)
*/
public void stateChanged(SensorPort aSource, int aOldValue, int aNewValue)
{
int value = sound.readValue();
if (value > 3)
{
synchronized (lock)
{
if (noiseStart <= 0)
{
noiseStart = System.currentTimeMillis();
} else
{
noiseEnd = System.currentTimeMillis();
}
}
}
}
}
|
|