How to use Speech Recognition along with Porcupine - android-studio

can anyone help me out on how to use speech recognition to listen right after porcupine wake up word. We need to some how figure out how to stop porcupine manager from listening the microphone until speech recognition is done listening to it.
try {
Log.i("YOU SAID IT!", "yesss");
porcupineManager = new PorcupineManager.Builder()
.setKeyword(Porcupine.BuiltInKeyword.JARVIS)
.setSensitivity(0.7f).build(
getApplicationContext(),
(keywordIndex) -> {
// This is where I need to somehow stop so that I can trigger speech recognition to listen
numUtterances++;
PendingIntent contentIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, MainActivity.class),
0);
final String contentText = numUtterances == 1 ? " time!" : " times!";
Notification n = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Wake word")
.setContentText("Detected " + numUtterances + contentText)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(contentIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(1234, n);
});
porcupineManager.start();
} catch (PorcupineException e) {
Log.e("PORCUPINE", e.toString());
}

Related

why android 8.0 oreo version not trigger the notification

I Made the Notification part in my developing mobile application. It's working perfectly in kitkat down versions as well as upper versions but oreo version. Oreo version it's not trigger the notification. what is the reason.. Following are my codes..
Alert Activity
List<Time> times = new ArrayList<>();
times.add(new Time(hour, mminute));
Intent intent = new Intent(this, MyBroadcastReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
for (Time time : times) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), broadcastCodeCus++, intent, 0);
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour));
cal_alarm.set(Calendar.MINUTE, Integer.valueOf(mminute));
cal_alarm.set(Calendar.SECOND, 00);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm > KITKAT & Alarm Set For: " + hour + " : " + mminute, Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm < KITKAT & Alarm Set For: " + hour + " : " + mminute, Toast.LENGTH_SHORT).show();
}
customText.append(broadcastCodeCus + ". " + time.hour + ":" + time.minute + "\n");
}
MyBroadcastReceiver
NotificationManager notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent= new Intent(context,secondActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent= PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,CHANNEL_ID)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.drink)
.setContentTitle(textTitle)
.setContentText(textContent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(textContent))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH) // >=API level 21
.setLights(Color.WHITE, 2000, 3000)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); // >=API level 21
notificationManager.notify(100,mBuilder.build());
}
In Android Oreo, it's a must to use a channel with your Notification Builder
you can follow the following code for the Notification Channel..
// Sets an ID for the notification, so it can be updated.
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.build();

Detect voice by audio recorder in android studio

Well, I would like to implement a function, such when the application starts, the recorder will start to recording, and when the user keeps silence there is nothing going to happen until the user speaks. Then, it will save the PCM file of user's voice and then stop recording.
Voice Detection in Android Application
Above is the question I have found similar as mine, but the answer of this link can not work. And I don't know how to modify it, since I don't understand the concept of the code.
Please help me~
Well, I solved my problem, here is my solution.
I modified the code came from this url:
Voice Detection in Android Application
private static final String TAG = "MainActivity";
private static int RECORDER_SAMPLERATE = 44100;
private static int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
private static int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private Button btn, btn_convert, btn_play;
private TextView txv;
boolean isRecording = false;
private File file;
private AudioRecord audioRecord;
int bufferSizeInBytes = 0;
Context context = MainActivity.this;
// path
final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/final.pcm" ;
final String outpath = path.replace(".pcm", ".wav");
public void autoRecording(){
// Get the minimum buffer size required for the successful creation of an AudioRecord object.
bufferSizeInBytes = AudioRecord.getMinBufferSize( RECORDER_SAMPLERATE,
RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING
);
// Initialize Audio Recorder.
AudioRecord audioRecorder = new AudioRecord( MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE,
RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING,
bufferSizeInBytes
);
// Start Recording.
txv.setText("Ing");
audioRecorder.startRecording();
isRecording = true;
// for auto stop
int numberOfReadBytes = 0;
byte audioBuffer[] = new byte[bufferSizeInBytes];
boolean recording = false;
float tempFloatBuffer[] = new float[3];
int tempIndex = 0;
// create file
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/final.pcm");
Log.d(TAG, "recording: file path:" + file.toString());
if (file.exists()){
Log.d(TAG,"file exist, delete file");
file.delete();
}
try {
Log.d(TAG,"file created");
file.createNewFile();
} catch (IOException e) {
Log.d(TAG,"didn't create the file:" + e.getMessage());
throw new IllegalStateException("did not create file:" + file.toString());
}
// initiate media scan and put the new things into the path array to
// make the scanner aware of the location and the files you want to see
MediaScannerConnection.scanFile(context, new String[] {file.toString()}, null, null);
// output stream
OutputStream os = null;
DataOutputStream dos = null;
try {
os = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(os);
dos = new DataOutputStream(bos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// While data come from microphone.
while( true )
{
float totalAbsValue = 0.0f;
short sample = 0;
numberOfReadBytes = audioRecorder.read( audioBuffer, 0, bufferSizeInBytes );
// Analyze Sound.
for( int i=0; i<bufferSizeInBytes; i+=2 )
{
sample = (short)( (audioBuffer[i]) | audioBuffer[i + 1] << 8 );
totalAbsValue += (float)Math.abs( sample ) / ((float)numberOfReadBytes/(float)2);
}
// read in file
for (int i = 0; i < numberOfReadBytes; i++) {
try {
dos.writeByte(audioBuffer[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
// Analyze temp buffer.
tempFloatBuffer[tempIndex%3] = totalAbsValue;
float temp = 0.0f;
for( int i=0; i<3; ++i )
temp += tempFloatBuffer[i];
if( (temp >=0 && temp <= 2100) && recording == false ) // the best number for close to device: 3000
{ // the best number for a little bit distance : 2100
Log.i("TAG", "1");
tempIndex++;
continue;
}
if( temp > 2100 && recording == false )
{
Log.i("TAG", "2");
recording = true;
}
if( (temp >= 0 && temp <= 2100) && recording == true )
{
Log.i("TAG", "final run");
//isRecording = false;
txv.setText("Stop Record.");
//*/
tempIndex++;
audioRecorder.stop();
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
The function of this function:
if you call this function, the recorder will start recording, and once you make sound(Notify if there are some noise it will stop too.) it will stop recording and save into file(pcm format).

Using ToneController to get more than one digit

I am new to UCMA and I read Tone Controller example in UCMA sdk 4.0.
I know this is the way you can record tone played by user:
void toneController_ToneReceived(object sender, ToneControllerEventArgs e)
{
Console.WriteLine("Tone Received: " + (ToneId)e.Tone + " (" + e.Tone + ")");
if ((ToneId)e.Tone == ToneId.Tone0)
{
_waitForToneReceivedEventCompleted.Set();
}
else
{
ToneController tc = (ToneController)sender;
tc.Send(e.Tone);
}
}
I want to know if there is a way to find the series of tones received from user not just one ( for example 10 digit), I want to use it for direct dialing.
You can simply do it in a loop:
string tone_received = "";
int number_of_tone_received = 0;
while(number_of_tone_received++ < 10)
{
//Sync; wait for ToneReceivedEvent
_waitForToneReceivedEventCompleted.WaitOne();
_waitForToneReceivedEventCompleted.Reset();
}
_waitForToneReceivedEventCompleted.WaitOne();
void toneController_ToneReceived(object sender, ToneControllerEventArgs e)
{
tone_received = tone_received + e.Tone;
_waitForToneReceivedEventCompleted.Set();
}

The need for the multithreading in javafx

I'm new to javafx and I have a question. My project is a voice browser with some simple command but I have an issue in switch(). The command at lines one and three of first case statement work, but line 2 does not. But if I remove the while loop, it works well! I have no idea how to solve this, help me please!
Here is my code
btSpeak.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
new Task<Void>(){
public Void call(){
int click=JOptionPane.showConfirmDialog(null, "Bạn đã sẵn sàng trải nghiệm với VoiceCommand chưa", "Speak", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(click==JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "Start", "Speak", JOptionPane.INFORMATION_MESSAGE);
// code for voice recognize
try {
URL url;
url = HelloWorld.class.getResource("helloworld.config.xml");
System.out.println("Loading..."+url.toString());
ConfigurationManager cm = new ConfigurationManager(url);
final Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
Microphone microphone = (Microphone) cm.lookup("microphone");
/* allocate the resource necessary for the recognizer */
recognizer.allocate();
/* the microphone will keep recording until the program exits */
if (microphone.startRecording())
{
System.out.println("Say: (Leen | Xuoongs| Trais | Phair | DDi |Veef| Dongs-Tab|Mowr-Tab| Noi - Dung| Trang-Chur|Trang-Truoc)") ;
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
/*
* This method will return when the end of speech
* is reached. Note that the endpointer will determine
* the end of speech.
*/
// Platform.runLater(new Runnable(){
// public void run(){
int i = 0;
while(i< 5) {
//Thread.this.notifyAll();
Result result = recognizer.recognize();
if (result != null)
{
int t = 0;
System.out.println("Enter your choise"+ "\n");
resultText = result.getBestFinalResultNoFiller();
System.out.println("You said: " + resultText + "\n");
if(resultText.equals("xuoongs")) {
t = 1;
} else if(resultText.equals("leen")) {
t = 2;
}
switch(t) {
case 1: {
JOptionPane.showMessageDialog(null, "xuống");//line 1
webEngine.executeScript("window.scrollBy(0,100)");line 2
break;// line 3
}
case 2: {
JOptionPane.showMessageDialog(null, "lên");
webEngine.executeScript("window.scrollBy(0,-100)");
break;
}
}// end switch
}// end if
}//end while()
}// end if
} catch (PropertyException e) {
System.err.println("Problem configuring HelloWorld: " + e);
e.printStackTrace();
}
}
}
}.run());
}// end button
});

bluetooth communication server client stuck j2me

How can I use the same Stream to read/write from server to client or from client to server more than once?
I am making a turn based game over bluetooth. Any ideas on how to achieve this in j2me?
I am using RfCOM protocol.
The client code is
public void serviceSearchCompleted(int transID, int respCode) {
try {
StreamConnection SC = (StreamConnection) Connector.open(connectionURL);
input = SC.openDataInputStream();
output = SC.openDataOutputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
while (true) {
f.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c.getLabel().toString().equalsIgnoreCase("send")) {
try {
output.writeUTF("Hey server");
output.flush();
String msg = input.readUTF();
System.out.println(msg);
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("am here now " + ex);
}
}
}
});
synchronized (lock) {
lock.notify();
}
}
}
Server code:
while (true) {
StreamConnection sc = scn.acceptAndOpen();
RemoteDevice rd = RemoteDevice.getRemoteDevice(sc);
DataInputStream input = sc.openDataInputStream();
DataOutputStream output = sc.openDataOutputStream();
String inMsg = input.readUTF();
System.out.println(inMsg + " recived at " + new Date().toString());
output.writeUTF("Hey client Sent at " + new Date().toString());
output.flush();
}
The stream works only once, then nothing happens when I click send again
Processing CONN_INIT 4
Processing CONN_OPEN 4
Processing CONN_SEND 4
Processing CONN_RECEIVE 4
Hey client Sent at Sun Jul 22 19:47:15 GMT+02:00 2012
Processing CONN_SEND 4
Processing CONN_RECEIVE 4
L2CAPConnectionNotifier.acceptAndOpen will block the loop and wait a new connection.
Move your code from the while body to a new thread.
while (true) {
StreamConnection sc = scn.acceptAndOpen();
final RemoteDevice rd = RemoteDevice.getRemoteDevice(sc);
new Thread() {
public void run() {
treatConnection(rd);
}
}.start();
}
private void treatConnection(RemoteDevice rd) {
DataInputStream input = sc.openDataInputStream();
DataOutputStream output = sc.openDataOutputStream();
String inMsg = input.readUTF();
while (inMsg != null) { // not sure about this stop condition...
System.out.println(inMsg + " recived at " + new Date().toString());
output.writeUTF("Hey client Sent at " + new Date().toString());
output.flush();
inMsg = input.readUTF();
}
}

Resources