android code to select audio mp3 and play it - android

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.

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;
}
}

Select an mp3 file from SD card

I need to ask the user to select a media file from his SD card for playing. The following code doesn't work:
edit:
after I choose a mp3 file from the sd card folder I can't start him (play him). I think that the problem is that it doesn't entering to the "onActivityResult" function.
Intent i = new Intent();
i.setType("audio/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, RESULT_OK);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==RESULT_OK)
{
Uri uri =data.getData();
if(uri!=null) {
try {
song.setDataSource(getApplicationContext(), uri);
song.prepare();
pl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
song.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(CONTEXT_RESTRICTED, RESULT_OK, data);
}
}
Your question doesn't include definitions of some variables so I added my own and it played. Try this:-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
Intent i = new Intent();
i.setType("audio/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Uri uri = data.getData();
if (uri != null) {
try {
MediaPlayer song = new MediaPlayer();
song.setDataSource(getApplicationContext(), uri);
song.prepare();
song.start();
} catch (Exception e) {
}
}
super.onActivityResult(CONTEXT_RESTRICTED, RESULT_OK, data);
}
}
MediaPlayer Docs here

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

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;
}

Video file taken from Android device not playing in app

I am trying to attach video file in my app. I tried the following code to get video from Android device. After attaching the video, if I try to play it using the MediaController class, the screen becomes blank. Please help me with this.
void pickVideo() {
Intent videoIntent = new Intent(Intent.ACTION_GET_CONTENT);
videoIntent.setType("video/*");
startActivityForResult(videoIntent, PICK_VIDEO_FILE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_VIDEO_FILE:
Uri videoUri = data.getData();
if (mChooseFileDialogListener != null) {
mChooseFileDialogListener.onVideoClick(videoUri, ViewModel.FILE_TYPE_VIDEO);
}
break;
}
}
ChooseFileDialogFragment.ChooseFileDialogListener mChooseFileDialogListener = new ChooseFileDialogFragment.ChooseFileDialogListener() {
#Override
public void onVideoClick(Uri videoUri, int fileType) {
mPath = videoUri.toString();
}
}
AttachmentAdapter.ItemClickListener = new AttachmentAdapter.ItemClickListener() {
#Override
public void onClick(String path) {
playVideo(path);
}
}
private void playVideo(String path) {
MediaController mediaControls = new MediaController(getActivity());
try {
//set the media controller in the VideoView
mBinding.videoPlayer.setMediaController(mediaControls);
//set the uri of the video to be played
if (file != null) {
mBinding.videoPlayer.setVideoPath(path);
}
} catch (Exception e) {
e.printStackTrace();
}
}

How to get pdf and doc files using Media.Files

Right Now I am getting my files using a particular piece of code which is working fine but in some of cell phones where there is no software like google drive I am getting message like no application installed for request. So I have searched and found that We can get files using Media.Files but not enough documentation is present to carry out the task.
Code:
warantyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf,application/msword");
Intent i = Intent.createChooser(intent, "File");
getActivity().startActivityForResult(i, FILE_REQ_CODE);
//Toast.makeText(getContext(),"Files",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_REQ_CODE) {
if (resultCode == RESULT_OK) {
String path="";
Uri uri = data.getData();
if (uri != null) {
try {
file = new File(getPath(getContext(),uri));
if(file!=null){
ext = getMimeType(uri);
sendFileToServer(file,ext);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}

Categories

Resources