I'm trying to play audio files with the built in mediaplayer in Android Studio. I'm using the code below to call an intent and open a third party file manager to get a files Uri and from that the file path whoich I store somewhere. Anyway, if I use a file manager like ES File Explorer I get a path that looks like "/sdcard/some directory/test.mp3" however, if I use the built in file explorer I get a path like "/documents/audio:1159" for the same file. I understand that the latter is an "asset" but when I try to feed this into mediaplayer I get an exception. What am I doing wrong?
The code below shows the intent method I'm using to get the filepath and the code below that shows how I use that file path to get a Uri and feed this into mediaplayer. Just to be clear file paths like "/sdcard/some directory/test.mp3" work fine. File paths like "/documents/audio:1159" don't.
final View.OnClickListener mGlobal_OnClickListener = new View.OnClickListener() {
public void onClick(final View v) {
int resID2 = v.getId();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
try {
startActivityForResult(intent,resID2); }
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please install a file manager",Toast.LENGTH_LONG).show();
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode == RESULT_OK)
{
Uri data = result.getData();
String thePath = data.getPath();
// Do something with the file path
}
}
Code used to start mediaplayer based on the file path retrieved from above
Uri myUri = Uri.parse(filePath);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {}
I guess you cannot use Uri like
/documents/audio:1159
when uses Intent MediaPlayer
EDITTED:
Try this code for getting filepath from assets folder
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
Related
I'm busy creating a soundboard app, and I'm struggling to figure the code so that a sound can be shared on email and whatsapp and other apps. I've done research and I tried to code it but with no luck. The audio file isn't even saving on the external storage so that I can share the sound from there. I have already written the permission uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE", and that all works. I think its my code on actually saving the audio to external storage.
public String copyFiletoExternalStorage(int resourceId, String resourceName){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Soundboard/sounds/" + resourceName;
try{
InputStream in = getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return pathSDCard;
}
As you can see from above I parse in R.raw.audio, and "audio.mp3" in the parameters of resourceId and resourceName respectively.
The code below shows how I share the audio once its been saved. But obviously because the audio isn't being saved then I cant share it.
share1 = findViewById(R.id.share1);
share1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sharePath = copyFiletoExternalStorage(R.raw.audio, "audio.mp3");
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound"));
}
});
If you have any idea why its not working please help me. I have tried so many different ways but nothing seems to work.
This question already has answers here:
Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?
(5 answers)
Android - Get real path of a .txt file selected from the file explorer
(1 answer)
Closed 2 years ago.
I am not geting currect path var name "FilePath" im geting value E/File path: /document/29 but my selected file stored in downloads folder file name is "test.xlsx" i need original path with file name with file extention to pass in FileInputStream().I am not able to fix it ...can anybody give the code
btnimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("*/*");
try {
startActivityForResult(fileintent, requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity can handle picking a file. Showing alternatives.");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String FilePath = data.getData().getPath();
Log.e("File path", FilePath);
if (FilePath.contains("/root_path"))
FilePath = FilePath.replace("/root_path", "");
Log.e("New File path", FilePath);
try {
if (resultCode == RESULT_OK) {
AssetManager am = this.getAssets();
InputStream inStream;
Workbook wb = null;
try {
inStream = new FileInputStream(FilePath);
Log.e("Extension",FilePath.substring(FilePath.lastIndexOf(".")));
if (FilePath.substring(FilePath.lastIndexOf(".")).equals(".xls")) {
Log.e("File Type", "Selected file is XLS");
wb = new HSSFWorkbook(inStream);
}
else if (FilePath.substring(FilePath.lastIndexOf(".")).equals(".xlsx")) {
Log.e("File Type", "Selected file is XLSX");
wb = new XSSFWorkbook(inStream);
}
else {
wb = null;
lbl.setText("Please select a valid Excel file");
return;
}
inStream.close();
i need original path with file name with file extention to pass in FileInputStream().
No you do not need 'a real path' as you better use the obtained uri to open an input stream.
InputStream is = getContentResolver().openInputStream(data.getData());
Use that stream as if it was your wanted stream.
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();
}
}
});
When I pick an image from gallery, I can get the Uri for that image as given below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
Uri uri = result.getData();
beginCrop(uri);
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, result);
}
}
The format of the Uri retrieved above is content://media/external/images/media/7266
However, I am unable to retrieve a Uri in this format when I try to fetch the Uri of an image I just saved as a file:
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
Bitmap bitmap = drawView.getResultBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File image = new File(sdCardDirectory, "DCIM/Camera/" + s.toString() + ".png");
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
MediaScannerConnection.scanFile(getActivity(), new String[]{
image.getAbsolutePath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
Uri uri = Uri.parse(image.getAbsolutePath());
beginCrop(uri);
The Uri obtained from above code is /storage/emulated/0/DCIM/Camera/02-04-16 12-49-16.png
I believe, this is not the correct Uri format, instead just absolute file path. Is there a way out by which I can get the Uri in the format content://media/external/images/media/ ?
Any help is much appreciated
I believe, this is not the correct Uri format, instead just absolute file path.
You are correct. Use Uri.fromFile() to convert a File into a Uri pointing to the file.
Is there a way out by which I can get the Uri in the format content://media/external/images/media/ ?
Not readily. At best, in onScanCompleted(), you might be able to run some query to get the Uri that the MediaStore uses. But, until then, MediaStore does not know about the file.
The Uri that you get from Uri.fromFile() is a valid Uri, but it will have a file scheme, not a content scheme.
you can get uri from Bitmap like this :
Uri getUri(Context context, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String path = "";
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
path = MediaStore.Images.Media.insertImage(
context.getContentResolver(), bitmap, "Title", null);
} catch (Exception e) {
}
return Uri.parse(path);
}
I have got so many links related to image file but didn't get any text related. There is solution for specific text file to open but I need general solution and not hard coded file location on SD card. I'm building an Android app that gets (copyies) the link of the file in TextView and reads the content of that file in another TextView from SD card. One button which is used to open the SD card:
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("text/plain"); //open only for text file
intent.setAction(Intent.ACTION_GET_CONTENT);
//broadcast the supported media to choose for file to open
startActivityForResult(Intent.createChooser(intent, "Select file"), MY_INTENT_CLICK);
}
This is the code for onActivityResult()
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == MY_INTENT_CLICK) {
if (data == null) return;
//String sel_file_path;
String sel_file_path;
Uri sel_file_uri = data.getData();
sel_file_path = FileText.getPath (getApplicationContext(), sel_file_uri);
setTextViews (sel_file_path);
}
}
}
After getting the file path from FileText it views the link and content of text file using this method.
//show the link and display the content of the file
private void setTextViews(String sel_file_path) {
//copy the file link to textview
this.txtpath.setText("File path: " +sel_file_path);
//display the text file
try {
File file1 = new File(sel_file_path);
//System.out.println("Path : " + file1);
FileInputStream fis = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String datatoread = "";
String inBuffer = "";
//Read the line of the file, store it in temporary variable and append it to inBuffer
while ((datatoread = br.readLine()) != null) {
inBuffer += datatoread + "\n";
}
txtdsp.setText(inBuffer);
br.close();
//Toast.makeText(getBaseContext(), "Load file reading", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
Log.d("MainActivity", "File Path: "+sel_file_path);
}
I got the an error while running on a device:
no such file or directory