how to get bytes from wav in android studio - android

i read lots of code for read byte from wav for android studio
but i still can not get byte from wav
really need codes or demo so i can get what i need
whats wrong with my code
Resources inn = getResources();
InputStream in = inn.openRawResource(R.raw.ccheer);
BufferedInputStream bis = new BufferedInputStream(in, 8000);
DataInputStream dis = new DataInputStream(bis);
byte[] music = null;
music = new byte[1024];
int i = 0;
try {
while (dis.available() > 0) {
music[i]=dis.readByte();
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
}

here is my new code. still cant read byte[]
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_AUDIO_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
System.out.println("Uri: " + uri);
InputStream is = new FileInputStream(getRealPathFromURI(this,uri));
}
}
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toByteArray();
}
whats wrong ? just want to read like this or other way ...
byte 00
byte 11
byte 22
...

Related

Unable to convert pdf or docx file to base64 in android

I am trying to first select PDF or docx file from memory then encode Base64 String and store in mysql database. When i click on upload button, it's not work. I think there was a problem in encode, but I'm unable to solve this problem. How to solve this problem or Is there any way to solve this issue??
Below is my code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
assert uri != null;
String uriString = uri.toString();
file = new File(uriString);
filepath = file.getAbsolutePath();
String displayName ;
if(uriString.startsWith("content://"))
{
Cursor cursor = null;
try {
cursor = this.getContentResolver().query(uri,null,null,null,null);
if(cursor!=null&&cursor.moveToFirst())
{
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.d("name",displayName);
}
}finally {
assert cursor != null;
cursor.close();
}
}else if(uriString.startsWith("file://"))
{
displayName = file.getName();
Log.d("name",displayName);
}
}
}
public static String convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 11];
int bytesRead;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(byteArray, Base64.NO_WRAP);
}
Indent in this way
public void getDoc() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
InputStream iStream = getContentResolver().openInputStream(selectedImage);
byte[] inputData = getBytes(iStream);
long fileSizeInBytes = inputData.length;
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;
ParseFile resumes = new ParseFile("image.pdf",
inputData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}

Copy audio from uri to specific directory

I get a song from the user's library like this:
Intent selectIntent = new Intent(Intent.ACTION_GET_CONTENT);
selectIntent.setType("audio/*");
startActivityForResult(selectIntent, SONG_REQUEST_CODE);
and retrieve it like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SONG_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if ((data != null) && (data.getData()!=null)) {
song = data.getData(); //song is an Uri defined previuosly
}
}
}
I need to import it into a folder I defined and created like this:
final File dir2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Chords/Imported Audio");
dir2.mkdirs();
I tried like this as suggested by Commonsware but the file is not created:
private void importAudio(Uri uri) {
String source = uri.getPath();
String destinationFile = dir2 + File.separator + songName;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(source));
bos = new BufferedOutputStream(new FileOutputStream(destinationFile, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The file is not there though. How can I fix this?
The file is not there though
Most likely, you have a stack trace in LogCat. song.getPath() is unlikely to be useful. song probably does not have a file scheme, and so getPath() is meaningless.
Use ContentResolver and openInputStream() to get an InputStream on song, then use that InputStream to copy the content.
Also:
Make sure that you have runtime permissions set up properly
Index the destination file so that it can be seen from more apps plus desktop OSes

How to convert the uri to inputStream data and upload the stream data into server?

I am working the task in picking the file from the gallery and upload the picked file to the server.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_FILE_REQUEST) {
if (data != null) {
//no data present
Uri uri = data.getData();
String filePath = data.getData().getPath();
// String path = uri.getPath();
file = new File(filePath);
String name = getContentName(getContentResolver(), uri);
try {
InputStream inStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
attachFile.addView(imageView);
TextView textView = new TextView(this);
textView.setText(name);
attachFile.addView(textView);
return;
}
}
}
I poicked the file by using intent
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//intent.addFlags(ST)
startActivityForResult(Intent.createChooser(intent, "Choose File to Upload.."), PICK_FILE_REQUEST);
My issue is the uri data is converted the inputStream but i am using the ion library in that inputstream files cannot be uploaded to server.
How to convert the inputStream to outputstream to save in getCacheDir().I refered this site How to get the file path for the picked files from the external storage in android?
Please help me how to upload the InputStream data into the ion library.
In the below code i have passed the uri into the inputstream and and then crated the file and inputStream data are written in outputstream.
This works 100% try this method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_FILE_REQUEST) if (data != null) {
//no data present
Uri uri = data.getData();
String filePath = data.getData().getPath();
String name = getContentName(getContentResolver(), uri);
File file = new File(getCacheDir(),name);
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Log.e("InputStream Size","Size " + inputStream);
int bytesAvailable = inputStream.available();
// int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size","Size " + file.length());
inputStream.close();
outputStream.close();
file.getPath();
Log.e("File Path","Path " + file.getPath());
file.length();
Log.e("File Size","Size " + file.length());
if(file.length() > 0){
attachementImage.setVisibility(View.INVISIBLE);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(bitmap);
attachFile.addView(imageView);
attachFile.addView(textView);
return;
}
}
}

How do I compress video from URI on Android?

I want to capture video and send it to the server in base64. Before sending it, I want to check the video length and video size. I am able to capture the video
switch (v.getId()) {
case R.id.camera_button:
intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, INTENT_VIDEO);
}
break;
}
}
and get the URI
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == INTENT_VIDEO && resultCode == RESULT_OK) {
Uri uri = data.getData();
}
}
I am able to get a video path
private String getPath(Uri video) {
String path = video.getPath();
String[] projection = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(media, projection, null, null, null);
if (cursor.moveToFirst()) path = cursor.getString(cursor.getColumnIndexOrThrow(projection[0]));
cursor.close();
return path;
}
How do I get a video object from that path so that I could compress, check video duration, file size?
For image, it will be as simple as this
BitmapFactory.decodeFile(photoPath);
and after that, I would like to convert it to base64.
For image, it's as simple as this
private String toBase64(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
byte[] bytes = outputStream.toByteArray();
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
Currently I am doing like this
private String toBase64(Uri video) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
String path = getPath(video);
File tmpFile = new File(path);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
long length = tmpFile.length();
int inLength = (int) length;
byte[] b = new byte[inLength];
int bytesRead;
while ((bytesRead = in.read(b)) != -1) {
baos.write(b, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
}
I get the base64, though I don't know if it's the correct one. but, I could not check video size, duration, etc.
you can compress video using ffmpeg. this is a sample project and this is the library.

Capture a video and store it at a specific location rather than a default location

I want to capture video and store video at specific location other than default location.
I know there is a method with MediaStore called setOutPutFile("String Location").
But it is not working properly.
I have seen many examples and performed but it stores video in default location only. Can someone help me solve this problem?
Do in this way :
Globally declare it
public static final int TAKE_PICTURE=0;
and then
Intent photoPickerIntent= new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Take Video"),TAKE_VIDEO);
In OnActivityResult Handle in this way:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if(requestCode==TAKE_VIDEO)
{
try
{
Log.e("videopath","videopath");
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"Directory Name");
if (!root.exists()) {
root.mkdirs();
}
File file;
file=new File(root,"android_"+System.currentTimeMillis()+".mp4" );
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Use below permissions:
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
I wasn't happy with any of the solutions provided here. Here's an extremely simple solution that will save the video in folder of your choice.
private static final int REQUEST_VIDEO_CAPTURE = 300;
private Uri videoUri;
private void dispatchVideoIntent(){
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File outputFile = new File("your file path goes here");
videoUri = Uri.fromFile(outputFile);
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK && videoUri != null) {
// do what you want with videoUri
}
}
The answer given by abhi here is correct, but i am writing a new answer to make it more easy and simple to other users.
To record a video, write this code in your onCreate method or on button click where you want to start the video recording
private static final int ACTION_TAKE_VIDEO = 3;
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
This code will start video recording.
Now below in your code after the onCreate method you need to override a method which name is onActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK)
{
try
{
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"/RecordVideo/"); //you can replace RecordVideo by the specific folder where you want to save the video
if (!root.exists()) {
System.out.println("No directory");
root.mkdirs();
}
File file;
file=new File(root,"android_"+System.currentTimeMillis()+".mp4" );
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Replace "RecordVideo" with the specific folder where you want to the video file on your sd card. You can also use any existing folder or directory name here.
Thanks

Categories

Resources