How to play recorded audio file from 'onActivityResult()'? - android

I'm using this library to record audio in my app.
Here's my code:
recordDefectAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(getBaseContext(),
android.Manifest.permission.RECORD_AUDIO) + ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_LOCATION);
}
if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.RECORD_AUDIO) +
ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
String filePath = Environment.getExternalStorageDirectory() + "/recorded_audio.wav";
int color = getResources().getColor(R.color.colorPrimaryDark);
AndroidAudioRecorder.with(MainActivity.this)
// Required
.setFilePath(filePath)
.setColor(color)
.setRequestCode(RECORD_PRODUCT_DAMAGE)
// Optional
.setSource(AudioSource.MIC)
.setChannel(AudioChannel.STEREO)
.setSampleRate(AudioSampleRate.HZ_48000)
.setAutoStart(true)
.setKeepDisplayOn(true)
// Start recording
.record();
}
}
});
and here's the code in onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECORD_PRODUCT_DAMAGE) {
if (resultCode == RESULT_OK) {
// Great! User has recorded and saved the audio file
Toast.makeText(this, "Audio recorded successfully!", Toast.LENGTH_SHORT).show();
playRecordedAudio.setVisibility(View.VISIBLE);
recordAgain.setVisibility(View.VISIBLE);
recordDefectAudio.setVisibility(View.INVISIBLE);
} else if (resultCode == RESULT_CANCELED) {
// Oops! User has canceled the recording
Toast.makeText(this, "Audio was not recorded", Toast.LENGTH_SHORT).show();
}
}
}
All I want to know is how can I play the audio file from the onActivityResult() or is there some other way of playing this audio?
Please let me know.

Use MediaPlayer to play audio file, write the below code in onActivityResult() , if (resultCode == RESULT_OK) get the path to the audio file from intent data
MediaPlayer mp=new MediaPlayer();
try{
mp.setDataSource("/sdcard/Music/maine.mp3");//path to your audio file here
mp.prepare();
mp.start();
}catch(Exception e){e.printStackTrace();}
}
See this for more info

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECORD_PRODUCT_DAMAGE) {
if (resultCode == RESULT_OK) {
// Great! User has recorded and saved the audio file
Toast.makeText(this, "Audio recorded successfully!", Toast.LENGTH_SHORT).show();
playRecordedAudio.setVisibility(View.VISIBLE);
recordAgain.setVisibility(View.VISIBLE);
recordDefectAudio.setVisibility(View.INVISIBLE);
String realPath = null;
Uri uriPath = null;
realPath = getPathForAudio(YourActivity.this, data.getData());
uriPath = Uri.fromFile(new File(realPath));
try{
MediaPlayer mp = MediaPlayer.create(context, uriPath);
mp.start();
}catch(NullPointerException e) {
// handle NullPointerException
}
} else if (resultCode == RESULT_CANCELED) {
// Oops! User has canceled the recording
Toast.makeText(this, "Audio was not recorded", Toast.LENGTH_SHORT).show();
}
}
}
Then get Audio file path
public static String getPathForAudio(Context context, Uri uri)
{
String result = null;
Cursor cursor = null;
try {
String[] proj = { MediaStore.Audio.Media.DATA };
cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor == null) {
result = uri.getPath();
} else {
cursor.moveToFirst();
int column_index = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
result = cursor.getString(column_index);
cursor.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}

Related

Get the user selected file's name and path irrespective of its location [ either in internal or external memory ] in Android?

Instead of the hard coded storage location in the code below, I would like to get the [name & path] of any Excelsheet that user selects, for data import operation. Found that getExternalStorageDirectory is deprecated, not sure how to achieve the requirement for accessing Excelfile from both Internal / External storage of Android.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case imrequestcode:
// Need help at this LOC where filepath could be user selected one.
String FilePath = "/mnt/sdcard/" + "sampleinput.xls";
try {
if (resultCode == RESULT_OK) {
//// Import function goes here
}
} catch (Exception ex) {
lbl.setText("Error " + e);
}
break;
}
}
Intent : Pick an excel sheet which has inputdata
bimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
fileintent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_LOCATION_ACCESS);
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_READ_EXTERNAL_STORAGE);
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
fileintent.setType("application/vnd.ms-excel");
try {
startActivityForResult(fileintent, importrequestcode);
fileintent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT > 22) {
requestPermissions(new String[]{"FLAG_GRANT_READ_URI_PERMISSION"}, 11);
}
} catch (ActivityNotFoundException e) {
lbl.setText("No file picker activity.");
}
}
});
}
To get the Filename:
private String getFileName(Uri uri) {
Cursor mCursor =
getApplicationContext().getContentResolver().query(uri, null, null, null, null);
int indexedname = mCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
mCursor.moveToFirst();
String filename = mCursor.getString(indexedname);
mCursor.close();
return filename;
}
To get the FilePath:
[Checkthislink](https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri/55469368#55469368)
Call the method and class in onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case imrequestcode:
Uri fileuri = data.getData();
String Nameoffile_selected = getFileName(fileuri);
String Pathoffile_selected = FileUtils.getPath(this, fileuri);
try {
if (resultCode == RESULT_OK) {
//// Import function goes here
}
} catch (Exception ex) {
lbl.setText("Error " + e);
}
break;
}
}

Why `onActivityResult()` is returning null data when recording an audio?

I'm using this library in my app for recording audio.
Here's my code:
String filePath;
recordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(getBaseContext(),
android.Manifest.permission.RECORD_AUDIO) + ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_LOCATION);
}
if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.RECORD_AUDIO) +
ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
filePath = Environment.getExternalStorageDirectory() + "/recorded_audio.wav";
int color = getResources().getColor(R.color.colorPrimaryDark);
AndroidAudioRecorder.with(MainActivity.this)
// Required
.setFilePath(filePath)
.setColor(color)
.setRequestCode(RECORD_PRODUCT_DAMAGE)
// Optional
.setSource(AudioSource.MIC)
.setChannel(AudioChannel.STEREO)
.setSampleRate(AudioSampleRate.HZ_48000)
.setAutoStart(true)
.setKeepDisplayOn(true)
// Start recording
.record();
}
}
});
Here's code in onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECORD_PRODUCT_DAMAGE) {
if (resultCode == RESULT_OK) {
// Great! User has recorded and saved the audio file
Toast.makeText(this, "Audio recorded successfully!", Toast.LENGTH_SHORT).show();
if (data == null) {
Toast.makeText(this, "Data is null", Toast.LENGTH_SHORT).show();
}
playRecordedAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uriPath = null;
uriPath = Uri.fromFile(new File(filePath));
try{
mp = MediaPlayer.create(getBaseContext(), uriPath);
mp.start();
}catch(NullPointerException e) {
// handle NullPointerException
}
}
});
} else if (resultCode == RESULT_CANCELED) {
// Oops! User has canceled the recording
Toast.makeText(this, "Audio was not recorded", Toast.LENGTH_SHORT).show();
}
}
}
Here, the Toast 'Data is null' is getting shown.
Why is this happening? Why am I unable to get the recorded audio file as the data here?
Please let me know.

data.getData() returns null in OnActvityResult while taking /Selecting Pictures from Camera and Gallery

I am developing an android app, which has a profile fragment where users can upload profile picture via taking picture or selecting from gallery. For now, everything is working fine via Activity.RESULT_OK. But the problem is the onActivityResult data.getData() that is returning nothing. I have made researches on this issue to no avail.
These are the two methods contained in my editprofile fragment.
private void setGalleryBtn() {
if (PermissionHandler.checkPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
AppHelper.LogCat("Read data permission already granted.");
new PickerBuilder(getActivity(), PickerBuilder.SELECT_FROM_GALLERY)
.setOnImageReceivedListener(imageUri -> {
Intent data = new Intent();
data.setData(imageUri);
AppHelper.LogCat("new image SELECT_FROM_GALLERY" + imageUri);
mEditProfilePresenter.onActivityResult(this, AppConst.SELECT_PROFILE_PICTURE, RESULT_OK, data);
})
.setImageName(getActivity().getString(R.string.app_name))
.setImageFolderName(getActivity().getString(R.string.app_name))
.setCropScreenColor(R.color.colorPrimary)
.withTimeStamp(false)
.setOnPermissionRefusedListener(() -> {
PermissionHandler.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
})
.start();
} else {
AppHelper.LogCat("Please request Read data permission.");
PermissionHandler.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
private void setCameraBtn() {
if (PermissionHandler.checkPermission(getActivity(), Manifest.permission.CAMERA)) {
AppHelper.LogCat("camera permission already granted.");
new PickerBuilder(getActivity(), PickerBuilder.SELECT_FROM_CAMERA)
.setOnImageReceivedListener(imageUri -> {
AppHelper.LogCat("new image SELECT_FROM_CAMERA " + imageUri);
Intent data = new Intent();
data.setData(imageUri);
mEditProfilePresenter.onActivityResult(this, AppConst.SELECT_PROFILE_CAMERA, RESULT_OK, data);
})
.setImageName(getActivity().getString(R.string.app_name))
.setImageFolderName(getActivity().getString(R.string.app_name))
.setCropScreenColor(R.color.colorPrimary)
.withTimeStamp(false)
.setOnPermissionRefusedListener(() -> {
PermissionHandler.requestPermission(getActivity(), Manifest.permission.CAMERA);
})
.start();
} else {
AppHelper.LogCat("Please request camera permission.");
PermissionHandler.requestPermission(getActivity(), Manifest.permission.CAMERA);
}
}
This is my EditProfilePresenter.onActivityResult method.
public void onActivityResult(Edit_profile_fragment myEdit_profile_fragment, int requestCode, int resultCode, Intent data) {
String imagePath = null;
if (resultCode == Activity.RESULT_OK) {
if (PermissionHandler.checkPermission(myEdit_profile_fragment.getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
AppHelper.LogCat("Read contact data permission already granted.");
switch (requestCode) {
case AppConst.SELECT_PROFILE_PICTURE:
imagePath = FilesManager.getPath(myEdit_profile_fragment.getActivity(), data.getData());
break;
case AppConst.SELECT_PROFILE_CAMERA:
if (data.getData() != null) {
imagePath = FilesManager.getPath(myEdit_profile_fragment.getActivity(), data.getData());
} else {
try {
String[] projection = new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA, MediaStore
.Images.ImageColumns.BUCKET_DISPLAY_NAME, MediaStore.Images.ImageColumns.DATE_TAKEN, MediaStore.Images
.ImageColumns.MIME_TYPE};
final Cursor cursor = myEdit_profile_fragment.getActivity().getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.ImageColumns
.DATE_TAKEN + " DESC");
if (cursor != null && cursor.moveToFirst()) {
String imageLocation = cursor.getString(1);
cursor.close();
File imageFile = new File(imageLocation);
if (imageFile.exists()) {
imagePath = imageFile.getPath();
}
}
} catch (Exception e) {
AppHelper.LogCat("error" + e);
}
}
break;
}
if (imagePath != null) {
EventBus.getDefault().post(new Pusher(AppConst.EVENT_BUS_IMAGE_PROFILE_PATH, imagePath));
} else {
AppHelper.LogCat("imagePath is null");
}
} else {
AppHelper.LogCat("Please request Read contact data permission.");
PermissionHandler.requestPermission(myEdit_profile_fragment.getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
}
Please what am I getting wrong?
You can Try this
if (requestCode == REQUEST_FROM_CAMERA && resultCode == RESULT_OK)
{
Bundle extras2 = data.getExtras();
if (extras2 != null) {
// do your stuff here
}
else {
// handle this case as well if data.getExtras() is null
Uri selectedImage = data.getData();
}
}
Hope it helps you

How to get image from gallery in android marshmallow?

Hi i am working in app were user can select image when he is registering an account. I am able to get image on lollipop but when i am testing it in marshmallow then i am not getting file and its name, I am able to ask permission from user and when i am selecting image from gallery i am not getting any file or its name
This is my Code
select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >=23) {
if (checkPermission()){
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}else{
requestPermission();
}
}else{
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
}
});
My Permissions
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(Register.this, Manifest.permission.READ_EXTERNAL_STORAGE );
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(Register.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(Register.this, "Write External Storage permission allows us to access images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Register.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
if(requestCode == PERMISSION_REQUEST_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Accepted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
}
}
After Selecting Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I am not getting why its not working in marshmallow even i have given permissions
I solved it.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}else {
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
When i was selecting file , then i was not going to this condition
if (filePath.getScheme().equals("content"))
so in else condition i have given this
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
To get image from gallery on any api level then follow this :
Copy and paste all 4 function to your activity
And call this to open gallery galleryPermissionDialog();
Variable used
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
protected static final int REQUEST_CODE_MANUAL = 5;
Permission need to add for lower than marshmallow
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Function 1:
void openGallry() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
Function 2 :
void galleryPermissionDialog() {
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(ActivityProfile.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ActivityProfile.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
} else {
openGallry();
}
}
Function 3 :
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(android.Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for READ_EXTERNAL_STORAGE
boolean showRationale = false;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (perms.get(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
galleryPermissionDialog();
} else {
showRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (showRationale) {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
galleryPermissionDialog();
}
});
} else {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ActivityProfile.this, "Please Enable the Read Storage permission in permission", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_MANUAL);
}
});
//proceed with logic by disabling the related features or quit the app.
}
}
} else {
galleryPermissionDialog();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Function 4 :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
/* final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
img_profile.setImageBitmap(selectedImage);*/
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
pictureFile = saveBitmapToFile(new File(picturePath));
Picasso.with(getApplicationContext()).load(new File(picturePath)).transform(new CircleTransform()).into(imgProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Function 5 :
public void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(ActivityProfile.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
file/* is not a valid MIME type. You should use / if you want to support any type of file. The files you see are unselectable because they are not of the correct MIME type.
With the introduction of virtual files in Android 7.0 (files that don't have a bytestream and therefore cannot be directly uploaded), you should most definitely add CATEGORY_OPENABLE to your Intent:
https://developer.android.com/about/versions/nougat/android-7.0.html#virtual_files
https://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//sets the select file to all types of files
intent.setType("*/*");
// Only get openable files
intent.addCategory(Intent.CATEGORY_OPENABLE);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,
"Choose File to Upload.."), PICK_FILE_REQUEST);
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
String filename =getFileName(yourfileuri);

android code to select audio mp3 and play it

I am developing an application,in which user will select a single audio file and play the audio.
Then I will pass the audio to the next activity.
Here is my code it select the audio but it gives error setDataSource Failed:Status=0X80000000 kindly guide me what should I do
switch(v.getId())
{
case R.id.btnmusic:
/*Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File file = new File("file:///sdcard/Music");
intent.setDataAndType(Uri.fromFile(file), "audio/*");*/
Intent pickMedia = new Intent(Intent.ACTION_GET_CONTENT);
pickMedia.setType("audio/*");
startActivityForResult(pickMedia,1);
break;
protected void onActivityResult(int RequestCode,int ResultCode,Intent data)
{
if(RequestCode==1)
{
if(data != null)
{
Uri muri=data.getData();
String uri=muri.getPath();
File track=new File(uri);
if(uri != null)
{
Uri urinew = MediaStore.Audio.Media.getContentUriForPath(track.getAbsolutePath());
//Toast.makeText(this, uri, Toast.LENGTH_SHORT).show();
MediaPlayer md=new MediaPlayer();
try{
md.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
md.setDataSource(AudioSelect.this, urinew);
md.prepare();
md.start();
}
catch(Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
}
else
{
Toast.makeText(this, "No Image Data Recieved", Toast.LENGTH_SHORT).show();
}
}
}
}
1: Use Intent to choose audio file from sd card:
Intent audioIntent = new Intent();
audioIntent.setType("audio/*");
audioIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(audioIntent,PICK_AUDIO_REQUEST);
2: Handle the result in OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null || data.getData() == null) {
// error
return;
}
if (requestCode == PICK_AUDIO_REQUEST) {
try {
Uri uri= data.getData();
String path = getRealPathFromURI(uri);
// play audio file using MediaPlayer
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: getRealPathFromURI is a utility method :
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getContext(), 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;
}
md = MediaPlayer.create(this, Uri.parse(track.getAbsolutePath()));
but i want to send this muri to next activity so i can play the song in next activity.please guide me how can i do this.
protected void onActivityResult(int RequestCode,int ResultCode,Intent data)
{
if(RequestCode==1)
{
if(data != null)
{
Uri muri=data.getData();
Intent intent = new Intent(this,NextActivity.class);
intent.putExtra("uriToPlay",muri);
startActivity(intent);
}
else
{
Toast.makeText(this, "No Image Data Recieved",
Toast.LENGTH_SHORT).show();
}
}
}
Rest of the code (like Media player) in the next Activity.

Categories

Resources