String path = Environment.getExternalStorageDirectory().toString()+"/Music/";
File directory = new File(path);
File[] mSongsList = directory.listFiles();
Uri mUri= Uri.fromFile(mSongsList[0]);
Log.v("MainActivity",mUri.toString());
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(this, mUri);
mMediaPlayer.prepare();
mMediaPlayer.start();
I am trying to play the first song in my list but,
i am getting an error on setDataSource.
it say "Unhandled Exception: java.io.IOException"
Place music files(s) under res/raw or any other folder under SD card. We are going to refer the audio file based on the Uri.
Create MediaPlayer object:
MediaPlayer mPlayer = new MediaPlayer();
Locate the audio file:
Uri myUri1 = Uri.parse("file:///sdcard/Songs/ARR Hits/hosannatamil.mp3");
Set the audio stream type of the media player:
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Set the data source as a content Uri:
try {
mPlayer.setDataSource(getApplicationContext(), myUri1);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI
correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI
correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI
correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
Prepare the player for playback, synchronously:
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI
correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI
correctly!", Toast.LENGTH_LONG).show();
}
Start the player:
mPlayer.start();
The above information has been taken from the below link:
"https://programmerguru.com/android-tutorial/android-mediaplayer-example-play-from-uri/"
Keep your code inside the try-catch block.
try{
// your code
}catch(IOException exception){
}
This is because you are trying to get the music file. If its not present then it will throw IOException, so you must handle this.
Replace Your Code Like below:
Note: Make Sure That You Have Some Music In MusicDirectory.
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
File directory = new File(path);
try{
File[] mSongsList = directory.listFiles();
Uri mUri= Uri.fromFile(mSongsList[0]);
Log.v("MainActivity",mUri.toString());
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(this, mUri);
mMediaPlayer.prepare();
mMediaPlayer.start();
}catch(IOException exception){
e.printStacktrace();
}
First of all make sure you have read permissions in your manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
If you are using the android version Marshmallow or above you need to ask the user for Runtime Permissions.
This is a good article to request runtime permissions.
For now you can go to the app info page and give the permissions manually. It will start working.
As in the image below :
You can play the song from your device by the following codes, but I don't know how to play next songs and previous songs , if you have any idea , pls share me.
fun getURI(){
val path: String =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath()
val directory = File(path)
try {
mSongsList= directory.listFiles()
val mUri = Uri.fromFile((mSongsList as Array<File>?)!![0])
Log.v("MainActivity", mUri.toString())
mp!!.reset()
mp!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
mp!!.setDataSource(this, mUri)
mp!!.prepare()
mp!!.start()
} catch (e: IOException) {
e.printStackTrace()
}
}
Related
I have some mp3 file in my web server.
I have to use in my app.
My mp3 on server might increase or decrease.(teacher would upload new file or delete old file
My mp3 name is T1.mp3, T2.mp3, T3.mp3, etc.
I have a next button,I hope when mp3 file not found,it would show it is last one.
EX: I am in T40.mp3 I click next to go to T41.mp3, but T41 was delete by teacher,
So, I would show this file not found.
I try it but it can not show and will be shutdown...
how can I do?
this is my code:
private ImageView.OnClickListener nextbtn=new ImageView.OnClickListener(){
#Override
public void onClick(View v) {
String tmp=url; //url=www.XXX......
T++;
tmp+="/"+filename[T]; //filename is number ex:T21.mp3
try {
totalTime=0;
mediaplayer.reset();
mediaplayer.setDataSource(tmp);
mediaplayer.prepare();
totalTime=mediaplayer.getDuration();
if(mediaplayer.getDuration()==0){
//show that mp3 is not found
mytoast("not found");
}
else{
totalTime=mediaplayer.getDuration();
}
mediaplayer.start();
} catch (IllegalStateException e) { }
catch (IOException e) { }
}
};
thanks
You can replace the 2 empty catch blocks with
catch (Throwable e) {
mytoast("not found"); // or something else happened
}
Also, check out this question, it by itself provides a method to check if a file is playable.
My question is why i need this permission when i'm trying to delete a file from the sdcard, as the permissions says 'Write' it doesn't write anything to the sdcard when i try to delete something so why is this required?
I tried removing the permission, but without it nothing works.
WRITE_EXTERNAL_STORAGE is a dangerous permission which i need to include in my privacy policy and i'm not sure how to explain this.
My permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
My code to delete a file
if (getActivity() != null) {
try {
treeUri = storageUtil.loadTreeUri();
if (!treeUri.equals("")) {
deleteFile(Uri.parse(treeUri), file);
Main.songs.deleteFile(getActivity(), songList.get(position).getData());
Main.songs.reScan(getActivity());
songList = Main.songs.getSongs();
//Send broadcast to update adapters
Intent intent = new Intent(Constants.ACTIONS.BROADCAST_UPDATE_ADAPTER2);
getActivity().sendBroadcast(intent);
if (!songList.isEmpty()) {
allSongsAdapter.updateList(songList);
}
} else if (treeUri.equals("")) {
((MainActivity) getActivity()).getSDCardAccess();
Toast.makeText(getActivity(), "First select directory with music files and try again.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
deleteFile method
private void deleteFile(Uri uri, File file){
if (getActivity() != null){
Intent intent = new Intent(Constants.ACTIONS.BROADCAST_UPDATE_PANEL_STATE);
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}
if (file.delete()){
Log.i(TAG,"internal delete!");
return;
}
if (getActivity() != null && file.exists()) {
DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), uri);
String filename = file.getName();
try {
getActivity().getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} catch (SecurityException e) {
Log.e(TAG, "SecurityException caught when deleting FilePath!", e);
}
Log.d(TAG, "fileName: " + filename);
if (pickedDir != null) {
DocumentFile documentFile = pickedDir.findFile(filename);
if (documentFile != null && documentFile.exists()) {
if (documentFile.delete()) {
Log.i(TAG, "Delete successful");
} else {
Log.i(TAG, "Delete unsuccessful");
}
}
}
}
}
This is the code i used from another post on here
Android SAF (Storage Access FrameWork): Get particular file Uri from TreeUri
There are two types of permissions.
1. To read content (read only access)
2. To modify content (read & write access)
Write access/permission is about modifying content on the disc.
Deleting a file is the same concept as issuing an rm via commandline in Unix. This unlinks the file (modifying the disk) which requires the write permission.
https://unix.stackexchange.com/a/10884
Deleting a file in any OS is the modification of master file table reference, which informs the OS where the file was located.
I want to recording a call voice but i get MediaRecorder:start failed : -2147483648
It's my call record code block
public void SesKayitBaslat(String number) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/ASesKaydi");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
//recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
Log.e("Eror","1");
e.printStackTrace();
} catch (IOException e) {
Log.e("Eror","2");
e.printStackTrace();
}
if(!recordstarted)
{
recorder.start();
recordstarted = true;
}
Log.e("Kayit:", "Başladı");
}
What is my error ? Can anyone help me ? I Tried MediaRecorder.AudioSource.VOICE_CALL AND MediaRecorder.AudioSource.VOICE_COMMUNICATION
When i used Voice_Communication type i didn't get voice of caller.
code 2147483648 refers to MEDIA_ERROR_SYSTEM (low-level system error).
Based on the documentation:
A BroadcastReceiver object is only valid for the duration of the call
to onReceive(Context, Intent). Once your code returns from this
function, the system considers the object to be finished and no longer
active.
In other words, the MediaRecorder instance that you expect to be there might actually not exist anymore since you're within a different BroadcastReceiver instance than the one that created the MediaRecorder. Its not a great idea to perform this task in BroadcastReceiver since it will only execute for 10 seconds after which System could declare app as not responding.
One solution would be to execute this code to Service
I generate a midi file and write it like this:
File output = new File("exampleout.mid");
I think I might need to change this, so it is in the right folder (just a readable/writable folder, perhaps Music/ )
Next I want to play this midi file with MediaPlayer, but I cannot figure out how to load the file.
mediaPlayer = MediaPlayer.create(this, R.raw.test3);
Only loads from the read only directory /res/raw. But if I try something like:
mediaPlayer = MediaPlayer.create(this, "file://exampleout");
It does not work because create needs an integer as input. I experimented with AssetFileDescriptor, but haven't figured it out yet.
Meanwhile, I want to generate a new midi file and load it in mediaPlayer (chained) to play when the first file finishes playing.
MediaPlayer mediaPlayer = MediaPlayer.create(Activity.this,R.raw.a1);
mediaPlayer.setOnCompletionListener(new musicCompletionListener());
mediaPlayer.start();
private class musicCompletionListener implements OnCompletionListener {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.setDataSource(WHATTOPUTHERE)
mediaPlayer.release();
}
}
My Problem is really how to call the file. I cannot use strings apparantly, and the r.raw directory is not possible due to its read only nature. I feel the solution is not so difficult, but I am just easing into java from c++, any help is much appreciated!
I stored the file in the cache dir, that works!
File output = new File(getCacheDir() + "/exampleout.mid");
And then calling the file:
String filePath = null;
File file = null;
FileInputStream inputStream = null;
try {
filePath = getCacheDir() + "/exampleout.mid";
file = new File(filePath);
inputStream = new FileInputStream(file);
if(inputStream.getFD().valid())
{
System.out.println("Valid!");
}
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(inputStream.getFD());
inputStream.close();
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You have to nicely design the Architecture of your app then only you can achieve what you have asked.
According to me you can do the following.
Design an interface with the method midiReady(uri of midi file)
This interface is implemented by your activity which contains mediaplayer
As soon as midi file is generation is completed call the method midiReady(uri of midi file)
Now since your activity implements the interface callback is invoked on your activity and you can set the mediaplayer to play the midi file since in callback you have uri of your midi file.
The above metinoed points are just a faint idea what you can do.With above faint idea you can go forward for implementation.
Hope this will help.
Thanks.
I am dynamically generating midi files (in cache dir) with an android app.
After generation, I play the file with MediaPlayer within the same app.
When running the app for the first time, it already needs the file to be there in the cache directory (the app crashes). It works on the emulator if I use the filemanager to put a dummy file there first. How can I circumvent this?
I need the app to run on a tablet for the first time, without requiring the file.
I am using these commands now:
try {
filePath = getCacheDir() + "/optimuse" + song + ".mid";
file = new File(filePath);
inputStream = new FileInputStream(file);
if (inputStream.getFD().valid()) {
System.out.println("Valid!");
}
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(inputStream.getFD());
inputStream.close();
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Is there any way around this?
Thanks!
Maybe check whether the file exists before using it? You can achieve this using the File#exists() method.
First, you use the Context#getFileStreamPath(String) method - where the String is the filename of the file you are trying to access. Then you can call File#exists() on the returned object.