Install Java MP3 library - gpio

I am working on a sound board for the raspberry pi with Java.
I used the libary Pi4j to make it possible to read Gpio pins.
To play a Mp3 we modified the code of an Pi4j example
button2.addListener(new GpioPinListenerDigital() {
#Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
// display pin state on console
System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
System.out.println(" Button Goat!");
play("goat.mp3");
}
});
our play method:
public static void play(String path) {
try {
FileInputStream FIS = new FileInputStream(path);
BufferedInputStream bis = new BufferedInputStream(FIS);
player = new Player(bis);
} catch (FileNotFoundException | JavaLayerException ex) {
}
new Thread() {
public void run() {
try {
player.play();
} catch (JavaLayerException ex) {
}
}
}.start();
}
When i put the java file on my RaspberryPi, and i compile the file i get this output
Image:
http://gyazo.com/0dc5e6cbe84ad00eed7d4a9df2b6b782
what i understand from this errors, is that the Libary's are not found.
how can i make this work?

Include the classpath to the javazoom lib on your command line.

Related

Camera cannot take image when app go background but work fine when app in foreground

I am making application which take image from front camera on firebase remote command. App work fine and take picture without user interaction, but when app close or go to foreground, app start giving error that Fail to connect to camera service. As soon as app open it capture the image.
I run foreground service notification which working but still same camera fail error and can not take picture.
try {
Log.d("kkkk", "Preparing to take photo");
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
int frontCamera = cam;
//int backCamera=0;
Camera.getCameraInfo(frontCamera, cameraInfo);
try {
camera = Camera.open(frontCamera);
} catch (RuntimeException e) {
Log.d("kkkk", "Camera not available: " + e.getMessage());
camera = null;
// takePicture(0);
}
try {
if (null == camera) {
Log.d("kkkk", "Could not get camera instance");
} else {
Log.d("kkkk", "Got the camera, creating the dummy surface texture");
try {
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
} catch (Exception e) {
Log.d("kkkk", "Could not set the surface preview texture");
e.printStackTrace();
}
camera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("kkkk", "clicked");
// Encode the byte array into a base64 string
// String imageString = android.util.Base64.encodeToString(imageBytes, android.util.Base64.DEFAULT);
// Log.d("error200", imageString);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
String path = "images/"+username.toLowerCase()+device.replace(" ","");
StorageReference imageRef = storageRef.child(path);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); // Replace this with your bitmap image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, baos);
byte[] data0 = baos.toByteArray();
UploadTask uploadTask = imageRef.putBytes(data0);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Log.d("pic","fail"+exception.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads
Log.d("pic","done");
}
});
camera.release();
}
});
}
} catch (Exception e) {
camera.release();
}
} catch (Exception e) {
Log.d("errorData", e.getMessage());
}
onDestroy method I release the camera but still same error.
#Override
public void onDestroy() {
super.onDestroy();
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}```
Can you add START_ACTIVITIES_FROM_BACKGROUND permission in the manifest if you have not added then you need to add this permission for using a camera in the foreground service. But I'm not sure the android newer version supports the used camera without user interaction
Please Refer Official Android Documentation here

How to read and write text data using Bluetooth plugin

Can someone please provide example code on how to use the Bluetooth cn1 library to read and write text data? I tried looking through the project source code (https://github.com/chen-fishbein/bluetoothle-codenameone) for example code, but could not find any that reads/writes text data using the appropriate methods. Those methods also don't have any Java docs.
Here's the code I'm using to send:
public void sendMessage(String message) {
if (Display.getInstance().isSimulator()) {
System.out.println(message);
} else {
// System.out.println("Sending message: " + message);
String b64WriteString = Base64.encode(message.getBytes());
try {
bt.write(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
}
}, deviceAddress, services.get(0), sendDataCharacteristic, b64WriteString, false);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
And here to receive:
private void registerNotifications() {
System.out.print("Registering notifications...");
try {
bt.subscribe(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
JSONObject dataIncoming = (JSONObject) evt.getSource();
String base64Value = "";
try {
if (dataIncoming.getString("status").equals("subscribedResult")) {
base64Value = dataIncoming.getString("value");
}
} catch (JSONException e) {
e.printStackTrace();
}
String message = new String(Base64.decode(base64Value.getBytes()));
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
messageReceived.set(message);
}
});
}
}, deviceAddress, services.get(0), receiveDataCharacteristic);
System.out.println("Registered");
System.out.println("Starting communication");
} catch (IOException e) {
System.err.println("Unable to register notifications " + e.getMessage());
e.printStackTrace();
}
}
I have fields defined for the service and characteristic UUID's. Also, the callSerially might not be needed anymore. I think I recall that the CN1LIB was updated to do that, but I don't remember for certain.
For that device, the service characteristic is "6E400001-B5A3-F393-­E0A9-­E50E24DCCA9E"
The sendCharacteristic is "0x0002"
The receiveCharacteristic is "0x0003"
After taking the suggestions of James H, and some more trial an error, I finally manage to get data transfer between the Adafruit's Bluefruit LE Friend working consistently, at least on an Android device. Not sure about iOS though, since I haven't tested it. Here are the critical code pieces needed.
First, you need the Service, TX and RX Characteristics UUIDs. These UUIDs were found here. Note, these don't need to be upper case.
public static final String UUID_SERVICE = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
public static final String UUID_RX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
public static final String UUID_TX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
Next, once you scanned and found the devices, call the connect() method to make the actual connection, and critically call the discover() method. Once the discover() callback gets called, then add the "subscriber" to receive data.
private void connect(String address) {
bleAddress = address; // set the global BLE address
if (!connected) {
// start an infinite progress dialog
final Dialog ip = new InfiniteProgress().showInifiniteBlocking();
try {
bt.connect(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ip.dispose();
Object obj = evt.getSource();
print("Connected to Bluetooth LE device ...\n" + obj, true);
// must be called on Android devices in order to load on the UUIDs, otherwise there is an error that service can't be found. Won't do anything on ios though?
discover();
connected = true;
}
}, address);
} catch (IOException ex) {
ip.dispose();
String message = "Error connecting to bluetooth device: " + address;
print(message + "\n" + ex.getMessage(), false);
}
} else {
String message = "BLE device already connected to: " + address;
print(message, false);
}
}
private void discover() {
try {
bt.discover(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
print("BLE Information Received ...", true);
addSubscriber();
}
}, bleAddress);
} catch (Exception ex) {
print(ex.getMessage(), false);
}
// if we running on is add the subscriber here since the above bt call
// does nothing?
if (Display.getInstance().getPlatformName().equals("ios")) {
print("Adding subscriber for iOS Device", true);
addSubscriber();
}
}
private void addSubscriber() {
try {
bt.subscribe(new ActionListener() {
StringBuilder sb = new StringBuilder();
#Override
public void actionPerformed(ActionEvent evt) {
JSONObject dataIncoming = (JSONObject) evt.getSource();
String base64Value = "";
try {
if (dataIncoming.getString("status").equals("subscribedResult")) {
base64Value = dataIncoming.getString("value");
}
} catch (JSONException e) {
console.setText("Error reading data: " + e.getMessage());
}
String message = new String(Base64.decode(base64Value.getBytes()));
sb.append(message);
if (message.endsWith("\r\n")) {
processData(sb.toString());
sb = new StringBuilder();
}
}
}, bleAddress, UUID_SERVICE, UUID_RX);
String message = console.getText() + "\nSubcriber added ...";
console.setText(message);
} catch (IOException ex) {
String message = "Error Subscribing: " + ex.getMessage();
console.setText(message);
}
}
So this sets up the connection, discovers the services, and finally adds the subscriber method which receives the data, and critically uses a buffer to collect the received data until the CRLF characters are received.
However, another major issue I ran into was the default 23 byte send limit (maybe an Android only issue?) of the BLE specification. If you tried sending more than this, the connection just gets dropped with no meaningful error message being returned. To get around this, I used the technique suggested here, which entails splitting data into chunks of 20 byte arrays. Since we sending regular ASCII text, then 20 characters should be 20 bytes, so I just split the text into Strings 20 characters long. Not the most efficient by it works and it easier to debug.
private void sendText(final String data) {
try {
String b64String = Base64.encode(data.getBytes());
bt.write(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if(data.endsWith("\r\n")) {
print("Data sent ...", true);
}
}
}, bleAddress, UUID_SERVICE, UUID_TX, b64String, false);
} catch (IOException ex) {
String message = "Error sending: " + data + "\n"
+ UUID_SERVICE + "\n"
+ UUID_TX + "\n"
+ ex.getMessage();
print(message, false);
}
}
private void splitAndSend(String text) {
text += "\r\n";
// first split data in chunk size of 20 chracters
ArrayList<String> sl = new ArrayList<>();
char[] data = text.toCharArray();
int len = data.length;
int chunkSize = 20;
for (int i=0; i < len; i+= chunkSize) {
sl.add(new String(data, i, Math.min(chunkSize,len - i)));
}
// now send chunks amd wait 100 ms to prevent any erros
for(String word: sl) {
sendText(word);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {}
}
}
The complete source code with GUI stuff can be found here, but this is definitely a work in progress.

how to stop MediaPlayer correctly?

I can stop the Audio but if I check my Android-Studio Debug windows, i see that the MediaPlayer works in Background !!!
I play the Sound like that :
try {
myMediaPlayer1 = new MediaPlayer();
myMediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);
myMediaPlayer1.setDataSource("http://myweb.com/audios/1.mp3");
myMediaPlayer1.prepare();
myMediaPlayer1.start();
} catch (Exception e) {
// TODO: handle exception
}
I stop the MediaPlayer via a click on a Button or OnDestry like that :
#Override
protected void onDestroy() {
super.onDestroy();
myMediaPlayer1.stop();
}
I debug via USB Connection. After Stop the Sound I see the MediaPlay works in Background :
You need to release media player using mediaPlayer.release(). If MediaPlayer is not playing any song/audio you shouldn't stop MediaPlayer. See below code for more help.
private void releaseMediaPlayer() {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}

Creating a Chat client with JavaFX using sockets

I am having trouble coding the socket side of a JavaFX chat client. This is my first time having to deal with socket in any sort of way, so some trouble was expected. I've been following this page to design the server-client side:
http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html
My problem is getting text I enter into the GUI into a DataInputSteam and DataOutputStream so that others on the same server can see the changes. I do
not understand how to convert the text in the UI to something the sockets
can work with.
Here is part of my controller class:
#FXML
private TextArea messageArea;
#FXML
private Button sendButton;
private ChatClient client;
#FXML
public void initialize() {
client = new ChatClient(ChatServer.HOSTNAME, ChatServer.PORT);
sendButton.setOnAction(event -> {
client.handle(messageArea.getText());
});
}
The ChatClient class is a Runnable with a DataInputStream and DataOutputStream field that connects to a Socket. I haven't changed much from the link:
public class ChatClient implements Runnable {
private Socket socket;
private Thread thread;
private DataInputStream streamIn;
private DataOutputStream streamOut;
private ChatClientThread client;
public ChatClient(String serverName, int port) {
System.out.println("Establishing connection...");
try {
socket = new Socket(serverName, port);
System.out.println("Connected: " + socket);
start();
} catch (UnknownHostException e) {
System.out.println("Unknown host: " + e.getMessage());
} catch (IOException e) {
System.out.println("Unexpected: " + e.getMessage());
}
}
#Override
public void run() {
while (thread != null) {
try {
streamOut.writeUTF(streamIn.readUTF());
streamOut.flush();
} catch (IOException e) {
System.out.println("Sending error: " + e.getMessage());
stop();
}
}
}
public void handle(String msg) {
try {
streamOut.writeUTF(msg);
streamOut.flush();
} catch (IOException e) {
System.out.println("Could not handle message: " + e.getMessage());
}
System.out.println(msg);
}
public void start() throws IOException {
streamIn = new DataInputStream(socket.getInputStream());
streamOut = new DataOutputStream(socket.getOutputStream());
if (thread == null) {
client = new ChatClientThread(this, socket);
thread = new Thread(this);
thread.start();
}
}
So in the controller class, I am calling the handle method which deals with the streams. The original code just wrote to the console, so I had to change the line:
streamIn = new DataInputStream(System.in)
to
streamIn = new DataInputStream(socket.getInputStream());
There is also a ChatClientThread class that extends Thread and just calls ChatClient.handle() in its run method.
I guess my question is how to update a GUI whenever writeUTF and readUTF interact with the DataStreams. I understand that streamOut.writeUTF(msg) changes the DataOutputStream to "have" that string, but I'm not sure how I'm supposed to use that datastream to update my gui so that all clients using the application can see the update. The way I have it now, if I run two instances of the JavaFX app, they dont' communicate through the UI or the console. My program just stalls whenever I click the send button

Implement video streaming in java me using rtsp

I want to implement video streaming in java me using rtsp url. When tested the code on devices, I get Media Exception stating Prefetch Error-33. Here's my code
private void startStreaming()
{
try
{
mplayer=Manager.createPlayer(videourl);
mplayer.addPlayerListener(this);
mplayer.realize();
videoControl=(VideoControl) mplayer.getControl("VideoControl");
if(videoControl!=null)
{
Item video=(Item) videoControl.initDisplayMode(videoControl.USE_GUI_PRIMITIVE, null);
videoControl.setVisible(true);
System.out.println("Playing");
Form v=new Form("Playing Video");
StringItem si=new StringItem("Status", "Playing....");
v.append(video);
display.setCurrent(v);
}
mplayer.prefetch();
mplayer.start();
}
catch(Exception noCanDo)
{
Form f=new Form("Error");
f.append("Error : "+noCanDo);
display.setCurrent(f);
}
}
I have also tried using alternative method of using MIDlet.platformrequest(videourl) method which invokes default internal player of device to play video file. The player is being started but later on, a connection timeout prompt occurs. I have however tested the rtsp url and it works very much fine. Any suggestions as to how can I do video streaming using rtsp url in java me?
Use this code for streamin RTSP,it should work for nokia symbian belle sdk 1.1 and nokia sdk 2.0
protected void startApp() throws MIDletStateChangeException {
VideoCanvas VC = new VideoCanvas(this,url);
Display.getDisplay(this).setCurrent(VC); }
}
//videoCanvas Class
public VideoCanvas(ExampleStreamingMIDlet midlet, String url) {
this.midlet = midlet;
this.url = url;
addCommand(start);
addCommand(stop);
addCommand(back);
addCommand(exit);
setCommandListener(this);
this.setFullScreenMode(true);
}
public void commandAction(Command c, Displayable arg1) {
if(c == start) {
start();
}
public void start() {
try{
Player player = Manager.createPlayer(url);
player.addPlayerListener(this);
player.realize();
control = (VideoControl)player.getControl("VideoControl");
if (control != null) {
control.initDisplayMode(VideoControl.USE_DIRECT_VIDEO,this);
control.setDisplaySize(176,144);
int width = control.getSourceWidth();
int height = control.getSourceHeight();
status2 = "Before: SW=" + width + "-SH=" + height + "-DW=" + control.getDisplayWidth() + "-DH=" + control.getDisplayHeight();
}
player.start();
}
catch(Exception e) {
Alert erro = new Alert("Erro",e.getMessage(),null,AlertType.ERROR);
Display.getDisplay(midlet).setCurrent(erro);
}
}
public void stop() {
if(player != null) {
player.deallocate();
player.close();
}
}

Resources