How to Play Audio File in Android

how to play audio file in android

Simply you can use MediaPlayer and play the audio file. Check out this nice example for playing Audio:

 public void audioPlayer(String path, String fileName){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();

try {
mp.setDataSource(path + File.separator + fileName);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}

how to play an audio file based on a string variable on Android

After long struggle I finally found the answer.

If myInput is the variable, then it is possible to use a String of the path , parse it to Uri and finally pass it into create(). I also used try-catch because I noticed that if the file is not found in the folder, then the app crashes. Here is the solution that worked for me:

    String uriPath = "android.resource://" + getPackageName() + "/raw/" + myInput;
Uri uri = Uri.parse(uriPath);
mp = MediaPlayer.create(this, uri);
try {
mp.start();
}
catch (Exception e) {}


Related Topics



Leave a reply



Submit