Android save Speech to Text audio - java

I am trying to create an app that will allow a user to upload an audio file created by Googles speech to text to a server. I have managed to get the URI for the audio file but how do I access it or convert it to a listenable format? I tried to play it back but nothing so far. This is what I have.
My Speech to text
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case REQ_CODE_SPEECH_INPUT: {
Bundle bundle = data.getExtras();
if(resultCode==RESULT_OK && null!= data){
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
vtt.setText(result.get(0));
Uri audioUri = data.getData();
uri.setText(String.valueOf(audioUri));
audioPath = uri.getText().toString();
}
break;
}
}
}
When I tried to play the audioPath variable. Nothing came out. How do I convert it to a listenable format?
Example of a uri that I got
content://com.google.android.googlequicksearchbox.AudioProvider/NoteToSelfOriginalAudio1.amr
Thank you for your help
I found somewhere that I should use content resolver and do something with the inputstream but Im not sure what.

I managed to solve the question.
The easiest way would be to use functions from apache commons IO
audioPath = uri.getText().toString();
finalPath = combinedPath.replaceAll(" ","");
Log.d("Filepath",combinedPath.replaceAll(" ",""));
ContentResolver contentResolver = getContentResolver();
try{
InputStream filestream = contentResolver.openInputStream(audioUri);
File targetFIle = new File(finalPath);
FileUtils.copyInputStreamToFile(filestream,targetFIle);
}catch (IOException e){
e.toString();
}

Button_to_speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent
= new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to text");
try {
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
}
catch (Exception e) {
Toast
.makeText(MainActivity.this, " " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
}
});

Related

Image and file operations on Android

I get pictures url from gallery or camera on android but I can't convert them to file. When i developing an app with Java in android, sometimes I need to get pictures from gallery and camera to my application. But when i try to do this I'm getting errors.
Isn't there a standard here? The code works at one api level and does not works another one. Or when I take the URI of some images and convert it to file, I get an error regardless of the api level. I wonder if there is a fundamental solution to this problem?
I am starting intent with this
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_RESULT);
And then I'm catching data with this code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == IMAGE_RESULT) {
String filePath = ImageFilePath.getPath(OwnProfileActivity.this, data.getData());
selectedFile = new File(filePath);
showProgressDialog();
Handler handler = new Handler();
handler.postDelayed(this::chaneProfileImage, 1000);
}
}
}
May I suggest something like this, but of course this is if you have a bitmap:
private fun getImageUriFromBitmap(image: Bitmap): Uri? {
val bytes = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.PNG, 100, bytes)
val relativeLocation = Environment.DIRECTORY_PICTURES + File.pathSeparator + "NotifyMe"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "notifyMe_${System.currentTimeMillis()}")
put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
}
return context?.contentResolver?.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
}
Then you can create the file with the uri
val file = File(uri.path)
source: https://gist.github.com/franciscobarrios/9f6634c87ca6e56ed70cd96807dd1dcb

How to check/set mime type in Android

Quick overview; I am building a Android application for file sharing, just began really but a little stuck on something. I want to enable the user to share multiple different file formats e.g. images, documents, videos etc. Now I got it all that working but only one at a time as show below. I have to change the string variable 'type' to certain mime type in order to open that file. I have the URI of the file that is selected if that helps.
I have Toasts in there just for testing purposes. Basically what I wish to achieve is that the application will check what file format is selected and open the apporiate third party app to preview that file when the preview button is clicked e.g. .JPG file will open pictures/gallery.
I believe code needs to be added to the 'previewBtn' in the onClick method but could be wrong.
Is there a way that the application can check what file is selected, and then set 'type' to be equal to that?
public class ShareFilesActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "ShareFilesActivity";
TextView mTextView = null;
String mimeType = null;
private static final int REQUEST_CODE = 6384; // onActivityResult request
// code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_files);
Button chooseFile;
chooseFile = (Button) findViewById(R.id.chooseFileBtn);
chooseFile.setOnClickListener(this);
Button previewBtn;
previewBtn = (Button) findViewById(R.id.previewBtn);
previewBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.chooseFileBtn:
showChooser();
break;
case R.id.previewBtn:
String input = mTextView.getText().toString();
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
String type = "image/*";
Toast.makeText(ShareFilesActivity.this, "Type3: " + type, Toast.LENGTH_LONG).show();
intent.setDataAndType(Uri.parse(input),type);
startActivity(intent);
Toast.makeText(ShareFilesActivity.this, input, Toast.LENGTH_LONG).show();
Toast.makeText(ShareFilesActivity.this, "Type1: " + mimeType, Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
private void showChooser() {
// Use the GET_CONTENT intent from the utility class
Intent target = FileUtils.createGetContentIntent();
// Create the chooser Intent
Intent intent = Intent.createChooser(
target, getString(R.string.chooser_title));
try {
startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// The reason for the existence of aFileChooser
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE:
// If the file selection was successful
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
final Uri uri = data.getData();
mimeType = getContentResolver().getType(uri);
Toast.makeText(ShareFilesActivity.this, "Type2: " + mimeType, Toast.LENGTH_LONG).show();
Log.i(TAG, "Uri = " + uri.toString());
mTextView = (TextView) findViewById(R.id.fileNameTextView);
mTextView.setText(uri.toString());
mimeType = getContentResolver().getType(uri);
try {
// Get the file path from the URI
final String path = FileUtils.getPath(this, uri);
} catch (Exception e) {
Log.e("ShareFilesActivity", "File Select Error", e);
}
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
To check mime type you can use the below function and change the type of your own use
public boolean isVideoFile(String path) {
String mimeType = URLConnection.guessContentTypeFromName(path);
System.out.println(mimeType);
return mimeType != null && mimeType.indexOf("video") == 0;
}
Will return true if the type is video on my case
Hope this helps.

Saving an image into my Gallery

I'm making an Android application in Android studio where the user can take a photo and save it into a new folder in their gallery. Currently the application takes the pictures fine but doesn't save the image into the new "SOC" folder in my gallery. I'm not getting any errors and I have no idea why it's not saving the image. Any help would be appreciated.
My code is as fallows
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage=Uri.fromFile(new File("/storage/emulated/0/DCIM/SOC","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
//Check for succesful result code
if (resultCode == -1) {
//Show your Toast when the result is a success.
Toast toast = Toast.makeText(getApplicationContext(),
"Picture is saved in your SOC gallery", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
}
}
}
I think you must manually add your new photo Uri to Media Content Provider.
take a look here
Call this method in your Activity for result
protected void addPhotoToGallery() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(getCurrentPhotoPath());
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
you should save the photo path before launching the intent and then getCurrentPhotoPath() must get that path

How can I save an image to my app?

I am making an app that will let users take photos and save them to the app, which will be password protected. So far, the app can take a picture, retrieve it, and set it to an image view. However, when I restart the app the image goes away. How can I save it?
int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
Uri imageUri;
public void takePic(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "filename_" +
String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra("data", imageUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
Bundle extras = data.getExtras();
Log.e("URI", imageUri.toString());
Bitmap bmp = (Bitmap) extras.get("data");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bmp);
}
else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
}
That imageUri you pass to the Intent- the image file is saved there. Just save the URI in SharedPreferences or other persistant storage and check that storage next time you launch your app.
This code is working on me :
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
}
else {
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (Exception e) {
Log.d("error", "cannot take picture", e);
}
}
This is how to define mFileTemp
String state = Environment.getExternalStorageState();
File mFileTemp;
if (Environment.MEDIA_MOUNTED.equals(state)) {
//this is like that
//any folder name/you can add inner folders like that/your photo name122412414124.jpg
mFileTemp = new File(Environment.getExternalStorageDirectory()+File.separator+"any folder name"+File.separator+"you can add inner folders like that"
, "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
else {
mFileTemp = new File(getFilesDir()+"any folder name"+
File.separator+"myphotos")+File.separator+"profilephotos", "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
Your global variables
private Uri mImageCaptureUri;
private File mFileTemp;
1) Define your global variables
2) Then define mFileTemp
3)Then trigger takePicture() method

Copy file from the directory to another , having the path's of file and directory

in my android application I want to copy file from one directory to another , I have the path of file filePath , and have the path of directory dirPath in what I must copy the file. I tried many ways , but nothing helped , some ways only make some empty(0 kb) file with strange name different from the name of my file. SO help please :)
here is some part of code, if it help's you, I have two buttons for Gallery and for Camera , and I must pick images from there
Button btnCam = (Button) dialog.findViewById(R.id.btncamera);
btnCam.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.cancel();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2500);
}
});
//end of camera button
Button btnGal = (Button) dialog.findViewById(R.id.btngalary);
btnGal.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.cancel();
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
and Activity Result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
url = new String(selectedImage.toString());
//here I must copy file with path `selectedImage` and replace it in
// directory with path `currentDir.hetPath()`
}
if (requestCode == 2500)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
//here I must do the same thing above
}
}
I found some way , in my Activity result I must call copyFile(String, String) function , here is the body
public static boolean copyFile(String from, String to) {
try {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
int end = from.toString().lastIndexOf("/");
String str1 = from.toString().substring(0, end);
String str2 = from.toString().substring(end+1, from.length());
File source = new File(str1, str2);
File destination= new File(to, str2);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
return true;
} catch (Exception e) {
return false;
}
}
If you feel up to it, you can include Apache Commons I/O in your app. I don't know how big it is. See Standard concise way to copy a file in Java?
Or maybe you could download the source, and cherry-pick the source to FileUtils.copyFile()

Categories