Get Audio Recorded by RecorderAudio Activity - android

I've searched a lot, but didnt found the solution to capture the audio recorded by Recorder Activity.
private void onClick() {
Intent intent = new Intent();
intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
try {
startActivityForResult(intent, IDF_ACTIVITY_AUDIO);
} catch (ActivityNotFoundException e) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IDF_ACTIVITY_AUDIO) {
final String folder = Environment.getExternalStorageDirectory() + "/myAudio/";
String pathAudio = data.getData().getPath();
Uri audioUri = data.getData();
// pathAudio == /external/audio/media/8
// audioUri /external/audio/media/8
File audio = new File(folder + "audioTest");
//how to getAudio from data and save in audio file???
}
}
}
This two methods show my problem. With the Uri object returned by Native Recorder Activity, I need to save the audio in my own file.
Anyone know how to do this??
Can you indicate some links to fully understand how Uri works?
EDIT:
The String '/external/audio/media/8' do not represent valid path. What this string means?

Look at Start audio recording with intent of MediaStore.Audio.Media.RECORD_SOUND_ACTION and Using Intent to record audio,
These both tutorial give you a URI after recording audio now using that uRI you can get absolute path of that file and you can also write that file where you want using simple File I/O operation.
EDIT:
new File(new URI(androidURI.toString()));

Hi i am also searching for storing the recorded files in my own folder
But you can get the exact file name using
String absolutepath=getRealPathFromURI(audioUri);
public String getRealPathFromURI(Uri contentUri)
{
String[] proj = { MediaStore.Audio.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = `enter code here`cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
System.out.println("absolutepath audiopath in getRealPathFromURI : "+cursor.getString(column_index));
return cursor.getString(column_index);
}

Related

How to convert a content Uri into a File

I know there are a ton of questions about this exact topic, but after spending two days reading and trying them, none seamed to fix my problem.
This is my code:
I launch the ACTION_GET_CONTENT in my onCreate()
Intent selectIntent = new Intent(Intent.ACTION_GET_CONTENT);
selectIntent.setType("audio/*");
startActivityForResult(selectIntent, AUDIO_REQUEST_CODE);
retrieve the Uri in onActivityResult()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AUDIO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if ((data != null) && (data.getData() != null)) {
audio = data.getData();
}
}
}
pass the Uri to another activity and retrieve it
Intent debugIntent = new Intent(this, Debug.class);
Bundle bundle = new Bundle();
bundle.putString("audio", audio.toString());
debugIntent.putExtras(bundle);
startActivity(debugIntent);
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
audio = Uri.parse((String) bundle.get("audio"));
The I have implemented this method based on another SO answer. To get the actual Path of the Uri
public static String getRealPathFromUri(Activity activity, Uri contentUri) {
String[] proj = { MediaStore.Audio.Media.DATA };
Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
and in the Debug activity's onCreate() I try to generate the file:
File audioFile = new File(getRealPathFromUri(this, audio));
This is how the error looks like:
Caused by: java.lang.NullPointerException
at java.io.File.(File.java:262)
at com.dancam.lietome.Debug.onCreate(Debug.java:35)
When I run the app I get a NPE on this last line. The audio Uri, isn't NULL though so I don't understand from what it is caused.
I'd really appreciate if you helped me out.
This is the library I'm trying to work with.
Note: I know exactly what NPE is, but even debugging I couldn't figure out from what it is caused in this specific case.
pass the Uri to another activity and retrieve it
Your other activity does not necessarily have rights to work with the content identified by the Uri. Add FLAG_GRANT_READ_URI_PERMISSION to the Intent used to start that activity, and pass the Uri via the "data" facet of the Intent (setData()), not an extra.
To get the actual Path of the Uri
First, there is no requirement that the Uri that you get back be from the MediaStore.
Second, managedQuery() has been deprecated for six years.
Third, there is no requirement that the path that MediaStore has be one that you can use. For example, the audio file might be on removable storage, and while MediaStore can access it, you cannot.
How to convert a content Uri into a File
On a background thread:
Get a ContentResolver by calling getContentResolver() on a Context
Call openInputStream() on the ContentResolver, passing in the Uri that you obtained from ACTION_GET_CONTENT, to get an InputStream on the content identified by the Uri
Create a FileOutputStream on some File, where you want the content to be stored
Use Java I/O to copy the content from the InputStream to the FileOutputStream, closing both streams when you are done
I ran into same problem for Android Q, so I end up creating a new file and use input stream from content to fill that file
Here's How I do it in kotlin:
private var pdfFile: File? = null
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
when (requestCode) {
REQUEST_CODE_DOC -> {
data.data?.let {
if (it.scheme.equals("content")) {
val pdfBytes =
(contentResolver?.openInputStream(it))?.readBytes()
pdfFile = File(
getExternalFilesDir(null),
"Lesson ${Calendar.getInstance().time}t.pdf"
)
if (pdfFile!!.exists())
pdfFile!!.delete()
try {
val fos = FileOutputStream(pdfFile!!.path)
fos.write(pdfBytes)
fos.close()
} catch (e: Exception) {
Timber.e("PDF File", "Exception in pdf callback", e)
}
} else {
pdfFile = it.toFile()
}
}
}
}
}
}
}
Daniele, you can get path of file directly from data like below in onActivityResult():
String gilePath = data.getData().getPath();

Android: Directory and file chooser android library

I'm using aFileChooser android library project in my app to select the file from external storage. but it doesn't seem to pick only directory to let user select the download location to download the files.
Is there any android library project which support both pick file and pick directory?
I understand there are multiple questions have been answered here either for file chooser or directory chooser but after extensive search I couldn't find one for both directory and file chooser.
Any help would be appreciated.
I have no android library project, but you can simply make your own file chooser with the next code. This code will ask you to chose a file browser, when you select a file in the file browser you'll get the path in the onActivityResult function in the FilePath String.
Create this public:
private static final int ACTIVITY_CHOOSE_FILE = 3;
When a button is clicked you can call this:
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("file/*");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
You can catch the directory with this code :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
String path = "";
if(requestCode == ACTIVITY_CHOOSE_FILE)
{
Uri uri = data.getData();
String FilePath = getRealPathFromURI(uri);
}
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query( contentUri, proj, null, null,null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Edit:
If you do not want to use an external file browser, you can import this android library into your project:
https://code.google.com/p/afiledialog/

Android Picking Sound File Path - Full Path Not Returned

I am trying to get the full path of a sound file on the SD card.
This launches sound picker - I then use the Play Music app to select a file
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setData(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_SOUNDPICKER);
On activity result I am trying to get the full path
case RESULT_SOUNDPICKER: {
Log.d("TAG", "onActivityResult "+requestCode+" "+resultCode);
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
String filePath = uri.getPath();
Log.d("TAG", "FilePath: "+filePath);
// A song was picked.
Log.d("TAG", "PickSongActivity.onActivityResult: "+data.getDataString());
}
}
But this returns a path like
//media/external/audio/media/13085
Rather than a proper path of where the file is held.
I need to get the full path back as I then want to use it to play the file.
Thank you.
Solution
This method can be used to get the full path.
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I need to get the full path back as I then want to use it to play the file.
There may not be a path (as it does not have to be a file), let alone a path that you can reach (as the file does not have to be on storage that is accessible to you).
MediaPlayer can use a Uri directly, so I suggest going that route.

saved Recorded Audio Using Audio intent cannot be played

I am making an app that allows that user to record audio. I used Audio intent for this. What I am trying to do is to record audio, set its name, and save it in a folder. In my code, the audio was saved and named properly but when I try to play it, it says that "Sorry, it cannot be played." I don't know where I go a mistake. Help me please, I will really appreciate it. Thanks.
Here is my code:
.....
private void dispatchTakeAudioIntent(int actionCode)
{
Intent takeAudioIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
File a = null;
try {
a = setUpAudioFile();
mCurrentAudioPath = a.getAbsolutePath();
takeAudioIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(a));
} catch (IOException e)
{
e.printStackTrace();
a = null;
mCurrentVideoPath = null;
}
startActivityForResult(takeAudioIntent, ACTION_TAKE_AUDIO);
}
private File setUpAudioFile() throws IOException {
File v = createAudioFile();
mCurrentVideoPath = v.getAbsolutePath();
return v;
}
private File createAudioFile() throws IOException
{
// Create an audio file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String audioFileName = AUDIO_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File audioF = File.createTempFile(audioFileName, AUDIO_FILE_SUFFIX, albumF);
return audioF;
}
private void galleryAddAudio()
{
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentAudioPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO:
{
if (resultCode == RESULT_OK)
{
handleBigCameraPhoto();
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
}
break;
}
case ACTION_TAKE_AUDIO:
{
if (resultCode == RESULT_OK) {
//audioFileUri = data.getData();
handleAudio(data);
//galleryAddVideo();
}
break;
}
} // switch
}
private void handleAudio(Intent data) {
audioFileUri = data.getData();
if (mCurrentAudioPath != null)
{
//audioFileUri = data.getData();
galleryAddAudio();
mCurrentAudioPath = null;
}
}
........
There are some limitations regarding RECORD_SOUND_ACTION intent that it is not supported to specify a file path to save the audio recording. The application shall save the audio in default location. You cannot use MediaStore.EXTRA_OUTPUT as extra because in document of MediaStore it is written under constant EXTRA_OUTPUT that it only use for image and video.
The name of the Intent-extra used to indicate a content resolver Uri to be used to store the requested image or video.
A solution to this cause is bit tricky. You can let the application save the audio to default but after you can cut, paste and rename your audio to your required location. I found two answers who claims that they found a way to cut paste.
Solution A
Solution B
Accept this answer or +1 if you find it useful.

How to get the file path from URI? [duplicate]

This question already has answers here:
Get filename and path from URI from mediastore
(32 answers)
Closed 10 years ago.
Please find my code below. I need to get the file path of the pdf document, selected by the user from SDcard. The issue is that the URI.getPath() returns:
/file:///mnt/sdcard/my%20Report.pdf/my Report.pdf
The correct path is:
/sdcard/my Report.pdf
Please note that i searched on stackoverflow but found the example of getting the filePath of image or video, there is no example of how to get the filepath in case of PDF?
My code , NOT all the code but only the pdf part:
public void openPDF(View v)
{
Intent intent = new Intent();
//intent.setType("pdf/*");
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), SELECT_PDF_DIALOG);
}
public void onActivityResult(int requestCode, int resultCode, Intent result)
{
if (resultCode == RESULT_OK)
{
if (requestCode == SELECT_PDF_DIALOG)
{
Uri data = result.getData();
if(data.getLastPathSegment().endsWith("pdf"))
{
String pdfPath = data.getPath();
}
else
{
CommonMethods.ShowMessageBox(CraneTrackActivity.this, "Invalid file type");
}
}
}
}
Can some please help me how to get the correct path from URI?
File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As #Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
Here is the answer to the question
here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}

Categories

Resources