Write bytes from audio live stream to file using php - java

My goal is to record live audio stream then save it on my website programmaticaly.
I already do this job using android app that runs on android physical phone or android emulator .. the app reads stream bytes then save it in a file then upload it to my website .. can i do this job directly using cpanel php?
Can i get bytes from live audio stream and open new file using php then write this bytes inside it and finally save this file?
Thanks in advance and execuse me if this question wrong or not logic.
Code in Android
try {
if (inputStream != null) {
if ((output = inputStream.read(bytes, 0, bytes.length)) != -1) {
buffer.write(bytes, 0, output);
}
}
} catch (IOException e) {
e.printStackTrace();
}

Related

Writing huge json object to file

So i have a huge JSONObject that I need to write to a file, right now my code work perfectly on 90% of the devices, the problem is on low memory devices such as Amazon Fire TV the app crashes with an error "java.lang.OutOfMemoryError".
I wonder is there another more memory friendly way to write that json object to file?
That's my code:
try{
Writer output = null;
if(jsonFile.isDirectory()){
jsonFile.delete();
}
if(!jsonFile.exists()){
jsonFile.createNewFile();
}
output = new BufferedWriter(new FileWriter(jsonFile));
output.write(mainObject.toString());
output.close();
} catch (Exception e) {
e.printStackTrace();
}

com.sun.net.httpserver freezes when user cancel downloading while server transferring file

com.sun.net.httpserver freezes when user cancel downloading while server transfering file
This is piece of implementation of java web-server (based on com.sun.net.httpserver) which serves static file downloading.
while ((count = fs.read(buffer)) > 0) {
try {
output.write(buffer, 0, count);
output.flush();
} catch (IOException e) {
System.out.print(e.getMessage() + "\n");
}
}
If user click Cancel in Save As dialog window while aforementioned piece of code still works the server freezes without throwing exception (I expect Broken Pipe exception).
Any suggestions on how to avoid freeze?

Getting data from an RS232 Port using Android Studio (Java)

Trying to get the weight from the weighing scale through a port connected to a USB that's connected to my android phone. The data is coming through but I don't know how to convert it properly. This is the code I'm currently using to convert the data:
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
This is what I'm currently getting:
The number 14700t was supposed to show on the textview.

Audio File in Amazon S3 and Java

I am trying to join two audio files stored in Amazon S3 using Java. Any ideas how to go about it? Should I use S3ObjectInputStream and then AudioInputStream? I tried that but I am getting unsupported file format error although it is a valid wav file. Please advise.
I too am trying to do this. So far this is what I got. We use the inputStream to write to a file because as far as I know there is no good way to take the stream and play from MediaPlayer.
Once we have the file we give the path to MediaPlayer and let it play. However my issues are that the audio file does not download completely. I think this has to deal with the buffer size. Also there is no pause or play so you will still need a GUI for that.
Don't forget to use this in a different thread than the main one.
String bucket = getContext().getString(R.string.bucketName);
String key = "somekey";
InputStream s3ObjectInputStream = s3.getObject(bucket,key).getObjectContent();
byte[] buffer = new byte[1024];
try {
File targetFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.mp4");
OutputStream outStream = new FileOutputStream(targetFile);
while( (s3ObjectInputStream.read(buffer)) != -1)
{
outStream.write(buffer);
}
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "temp.mp4");
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}

Attempting to overwrite files results in blank files

In the app I am working on right now, part of the functionality is to write data saved on the device to a flash drive connected via a USB-OTG adapter. Specifically, the device is a rooted Motorola Xoom running 4.2.2. I can successfully write files to the drive and read them on my computer. That part works fine. However, when I try to replace existing files with new information, the resulting files come out empty. I even delete the existing files before writing new data. What's weird is that after copying the contents of my internal file to the flash drive, I log the length of the resulting file. It always matches the input file and is always a non-0 number, yet the file still shows up as blank on my computer. Can anyone help with this problem? Relevant code from the AsyncTask that I have doing this work is below.
#Override
protected Void doInBackground(Void... params) {
File[] files = context.getFilesDir().listFiles();
for (File file : files) {
if (file.isFile()) {
List<String> nameSegments = Arrays.asList(file.getName().split(
"_"));
Log.d("source file", "size: " + file.length());
String destinationPath = "/storage/usbdisk0/"
+ nameSegments.get(0) + "/" + nameSegments.get(1) + "/";
File destinationPathFile = new File(destinationPath);
if (!destinationPathFile.mkdirs()) {
destinationPathFile.mkdirs();
}
File destinationFile = new File(destinationPathFile,
nameSegments.get(2));
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(file);
fw = new FileWriter(destinationFile, false);
int c = fr.read();
while (c != -1) {
fw.write(c);
c = fr.read();
}
fw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fr.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d("destination file", "size: " + new File(destinationFile.getPath()).length());
}
}
return null;
}
EDIT:
Per #Simon's suggestion, I added output.flush() to my code. This does not change the result.
EDIT #2:
I did some further testing with this and found something interesting. If I go to Settings->Storage->Unmount USB Storage after writing to the flash drive but before removing it from the OTG adapter, everything works perfectly. However, failing to eject the drive after writing results in the data not being written. What's strange is that the folder structure and file itself are created on the drive, but the file is always empty. One more thing: if I go to a file manager application and open up the file prior to removing the drive, the files all exist as they should. However, even removing the device, plugging it straight back in to the tablet and opening any of the files results in the file looking empty. I can't make heads or tails of this, and this is incredibly frustrating. Can anyone help with this?
EDIT #3:
I also changed to using FileReaders and FileWriters just to wee what would happen. I don't care about efficiency at this point, I simply want file writing to work reliably. This change did not affect the issue. Updated code is posted above.
Try using FileReader.ready() method before your FileReader.read() call,
and ensure if your FileReader really has some bytes in it.
Try this , Used buffered reader for writing
try
{
fw = new FileWriter(destinationFile);
BufferedWriter writer=new BufferedWriter(fw);
writer.append(yourText); // Append can be changed to write or something if you want to overwrite
writer.close();
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
if (fw != null) {
try {
fw.flush();
fw.close();
}
catch (IOException e) {
}
I found the solution to my problem. It appears that the Android system buffers some files off of the SD card/flash drive, and then writes them to the flash drive upon eject. The following code after my file operations synchronizes the buffer with the filesystem and allows the flash drive to be immediately removed from the device without data loss. It's worth noting that this DOES require root access; it will not work on a non-rooted device.
try {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("sync; sync\n");
os.writeBytes("exit\n");
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
Source of my solution: Android 2.1 programatically unmount SDCard
It sounds like the filesystem is caching your changes, but not actually writing them to the flash drive until you eject it. I don't think there's a way to flush the filesystem cache, so the best solution seems to be just to unmount and then remount the flash drive.

Categories