I want to save pcm file format file to be store in folder and that folder to be saved on SD card. So far I can save only one file of pcm audio file on SD card. I have tried to store more than one pcm files on SD card but then an error occurred. The error was that I didn't record file. Every time I record some sound, file length remain zero kb.
private void startRecord() {
File path = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MYfolder/");
// File file = new File(path,"myrecording.pcm");
path.mkdirs();
// file = new File(path, "myrecording.pcm");
// // File file = new File(Environment.getExternalStorageDirectory(),
// // "test.pcm");
//
int sampleFreq = 11025; /* (Integer)spFrequency.getSelectedItem(); */
try {
audiofile = File.createTempFile("myrecording", ".pcm", path);
// recorder.setOutputFile(audiofile.getAbsolutePath());
// file.createNewFile();
// File.createTempFile("myrecording", ".pcm", file);
// OutputStream outputStream = new FileOutputStream(file);
OutputStream outputStream = new FileOutputStream(
audiofile.getAbsoluteFile());
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(
bufferedOutputStream);
int minBufferSize = AudioRecord
.getMinBufferSize(sampleFreq, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
sampleFreq, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, minBufferSize);
audioRecord.startRecording();
while (recording) {
int numberOfShort = audioRecord.read(audioData, 0,
minBufferSize);
for (int i = 0; i < numberOfShort; i++) {
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
addRecordingToMediaLibrary();
}
protected void addRecordingToMediaLibrary() {
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/pcm");
values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
ContentResolver contentResolver = getContentResolver();
Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(base, values);
sendStickyBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
newUri));
Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
}
i have edited my code, i want to save pcm file on sdcard with in specific folder through content resolver. I am get memory leakage error don't known how to solve that.
YOUR_FILE_NAME it should be diffrent every time, use datetime to set file name diffrent
private void startRecordinga() {
AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}
//convert short to byte
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
private void writeAudioDataToFile() {
// Write the output audio in byte
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/Myfolder/"+YOUR_FILE_NAME+".pcm";
short sData[] = new short[BufferElements2Rec];
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
recorder.read(sData, 0, BufferElements2Rec);
System.out.println("Short wirting to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
// stops the recording activity
if (null != recorder) {
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
}
Related
I am trying to download an e-book from URL and unzip it, which further goes for display. While the same unzip logic works perfectly for a FTP download, when it comes to URL, unzipping method does nothing after download.
My book download calling method :
DownloadBook db = new DownloadBook(localFile,"some url",book.key,context,(TaskListener) result -> {
if (result) {
runOnUiThread(() -> pBar.setVisibility(View.VISIBLE));
Runnable t = (Runnable) () -> {
unzip(localFile.getPath(), b.key.replace(".zip",""), b);
isDownloaded = true;
//Deleting downlaoded zip file
System.out.println("zip file deleted - "+localFile.delete());
String urls = localFile.getPath() + "/" + ((b.key).replace(".zip", ""));
System.out.println("URL IS " + urls);
System.out.println("Going for Display");
GlobalVars.title = b.title;
Intent intent = new Intent(My_Library.this, DisplayActivity.class);
startActivity(intent);//
};
t.run();
} else {
runOnUiThread(() ->
{
alert = new AlertDialog.Builder(this);
alert.setTitle("Error");
alert.setMessage("Could not download. Please try again !")
.setCancelable(true)
.setNegativeButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(My_Library.this, My_Library.class);
startActivity(intent);
dialog.cancel();
}
});
alert.create();
alert.show();
}
);
}
});
The zip file download method :
t = new Thread(new Runnable() {
#Override
public void run() {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("some url");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(localFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
System.out.println("Total is "+total);
if(fileLength>0)
{
System.out.println("File length is "+fileLength+" local file length is "+localFile.length());
percent = (int) (total * 100 / fileLength);
System.out.println("FTP_DOWNLOAD bytesTransferred /downloaded -> " + percent);
mProgress.setProgress(percent);
}
output.write(count);
output.flush();
}
mListener.finished(true);
} catch (Exception e) {
e.printStackTrace();
mListener.finished(false);
} finally {
try {
output.flush();
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
The unzip method
public void unzip(String _zipFile, String _targetLocation, Book b) {
pBar.setVisibility(View.VISIBLE);
GlobalVars.path = _targetLocation;
_targetLocation = getApplicationContext().getFilesDir().getPath();
dirChecker(_targetLocation);
try {
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(_zipFile));
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("Unzipping file -> " + ze.getName());
//create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
} else {
File f = new File(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
dirChecker(f.getParent());
long size = f.length();
BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(new File(String.valueOf(f.getAbsoluteFile()))));
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
fout.write(buffer, 0, read);
}
zin.closeEntry();
fout.close();
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
The FTP download class method Unzip works absolutely fine. But as I try to put download from url, it just downloads but not unzips.
You have to change the output buffer writing method.
So instead of, in zip download method
output.write(count);
Use,
output.write(data,0,count);
Here I am trying to upload multiple files on google drive app folder:
#Override
protected Boolean doInBackground(DriveFile...params) {
Drive.DriveApi.requestSync(mGoogleApiClient).await();
DriveFile file = params[0];
try {
DriveApi.DriveContentsResult driveContentsResult = file.open(
mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(DbHelper.databasePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(driveContents.getOutputStream());
/*reading and writing data to and from file*/
int n = 0;
byte[] data = new byte[8 * 1024];
try {
while ((n = bufferedInputStream.read(data)) > 0) {
bufferedOutputStream.write(data, 0, n);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
com.google.android.gms.common.api.Status status =
driveContents.commit(mGoogleApiClient, null).await();
return status.getStatus().isSuccess();
}
return false;
}
While trying to upload two files the doInBackground method gets called only once and only one file gets uploaded which is last in an arraylist of files.
You need to post the complete code which is calling the doInBackground. The issue is with that part of code.
backupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createFolderOnGoogleDrive();
multipleFilesArrayList = listFilePath();
createFileAsyncTask = new CreateFileAsyncTask();
multipleFilestoAsynchTask = multipleFilesArrayList.get(i);
createFileAsyncTask.execute(multipleFilesArrayList);
}); }
I am trying to Copy file from internal memory card to external memory card
By googling i found this answer
try {
InputStream in = new FileInputStream("/storage/sdcard1/bluetooth/file7.zip"); // Memory card path
File myFile = new File("/storage/sdcard/"); //
OutputStream out = new FileOutputStream(myFile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
session.showToast("file copied sucessfully");
} catch (FileNotFoundException e) {
showToast(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
showToast(e.getMessage());
e.printStackTrace();
}
its work for internal move to internal or external storage to external
but cross transferring do not work its throws an error Erofs read only file system
Try some thing like this:
new FileAsyncTask().execute(files);
and
// AsyncTask for Background Process
private class FileAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ActivityName.this, "Your Title", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
// Function to copy file to the SDCard
public void copyFileToSDCard(String fileFrom){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFrom);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/MyProject", fileFrom));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
Try this, Replace this line:
File myFile = new File("/storage/sdcard/");
with:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File myFile = cw.getDir("imageDir", Context.MODE_PRIVATE);
Check this link, may be helpfull: click here
I am using tesseract OCR in my app (Spl!t). When I launch the app from Eclipse to my phone, eng.traineddata is copied into /storage/emulated/0/Pictures/Receipts/tessdata/. But when I installed the app from the market, the eng.traineddata file is not copied into the folder. Is there something wrong with my code?
private File getOutputPhotoFile() {
directory = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Receipts");
dataPath = directory.getAbsolutePath();
if (!directory.exists()) {
directory.mkdirs();
Toast.makeText(Trans_List.this, "Receipts Folder Created", Toast.LENGTH_SHORT).show();
File tessDir = new File(directory, "tessdata");
if (!tessDir.exists()) {
tessDir.mkdirs();
Toast.makeText(Trans_List.this, "Tessdata Folder Created", Toast.LENGTH_SHORT).show();
File trainingData = new File(tessDir, "eng.traineddata");
if(!trainingData.exists())
new CopyLibrary().execute(LANG);
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
.format(new Date());
return new File(directory.getPath() + File.separator + "Receipt_"
+ timeStamp + ".jpg");
}
private class CopyLibrary extends AsyncTask<String, Void, Void> {
private void copyFile(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
out.write(buffer, 0, read);
}
#Override
protected Void doInBackground(String... s) {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("Spl!t", "Failed to get asset file list.");
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(dataPath + File.separator
+ "tessdata" + File.separator, LANG
+ ".traineddata");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
Toast.makeText(Trans_List.this, "Tessdata copied", Toast.LENGTH_SHORT).show();
out = null;
} catch (IOException e) {
Log.e(TAG, "Failed to copy asset file");
}
}
return null;
}
}
How to unzip programming android from asset to /sdcard/, my code in below not success in nexus7, but if it is run in addition to nexus7 will be fine, will be able to extract the data.
To running unzip.
new Thread(new Runnable() {
#Override
public void run() {
UnZip.start();
}
}).start();
private Thread UnZip = new Thread() {
#Override
public void run() {
try {
final int BUFFER = 8192;
ZipInputStream inputStream = new ZipInputStream(getAssets().open("file.zip"));
for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
.getNextEntry()) {
String innerFileName = "/sdcard/" + File.separator
+ entry.getName();
File innerFile = new File(innerFileName);
if (entry.isDirectory()) {
innerFile.mkdirs();
} else {
FileOutputStream outputStream = new FileOutputStream(
innerFileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream, BUFFER);
int count = 0;
byte[] data = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1) {
bufferedOutputStream.write(data, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
inputStream.closeEntry();
inputStream.close();
} catch (Exception e) {
}
}
};
instead of look for sdcard in this way
String innerFileName = "/sdcard/" + File.separator
+ entry.getName();
use the Environment API
String innerFileName = Environment.getExternalStorageDirectory().toString() + File.separator + entry.getName();
do not forget to add the WRITE_EXTERNAL_STORAGE permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>