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.
Related
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()
}
}
I'm trying to save user information in a single save file in local directory. However every time I run the app, the information doesn't save--I can tell by rerunning the app and the file data isn't updated or returning to the activity and finding out the data displayed isn't updated upon returning to the same activity. Here is the function in the activity where I set up a file output stream and decided to write in the information through a string containing all the User information and display "FILE CLOSED" once I assumed the file has written. Could you spot any missing steps or anything that I missed so that the file can be written?
public void saveToFile() throws FileNotFoundException{
//new filestream
FileOutputStream fostream;
fostream = openFileOutput(fileName, Context.MODE_PRIVATE);
//Write into file for each User in Array
for (int i = 0; i < userArrayList.size(); i++){
String contents = userArrayList.get(i).display();
System.out.println(userArrayList.get(i).display());
try {
fostream.write(contents.getBytes());
} catch (IOException e) {
System.out.println("NOTHING WRITTEN");
e.printStackTrace();
}
}
try {
fostream.close();
System.out.println("FILE CLOSED");
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks so much for your help!
I have read the instructions step by step
https://developers.google.com/drive/quickstart-android
And I have run the example then it works. When insert a file. It will make a lot duplicated file on google drive . I insert "test.db" many time on google drive. It create a lot of test.db. Therefore before I start insert "test.db", I want to delete the "test.db" first.
But the following code still not work. Could any body tell me why?
private void deleteFileOnDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Files.List fileList = service.files().list().setQ("title = 'test.db'");
FileList files = fileList.execute();
ArrayList<File> myFiles = new ArrayList<File>();
myFiles.addAll(files.getItems());
for (File myFile : myFiles) {
deleteFile(service, myFile.getId());
}
}
catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
finish();
}
}
});
t.start();
}
private static void deleteFile(Drive service, String fileId) {
try {
service.files().delete(fileId).execute();
}
catch (IOException e) {
System.out.println("An error occurred: " + e);
}
}
I spend 2hours to integrate the dropbox into our android app. It works fine. But I have spent 2 days to integrate google drive into our android app. It still not be finish yet. sigh~
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.