how to play audio file in android
@Niranjan, If you are using a raw file from res/raw folder, ie., reading a file stored inside the project, we can use:
mediaplayer.setDataSource(context, Uri.parse("android.resource://urpackagename/res/raw/urmp3name");
If you have to use from SD card:
MediaPlayer mediaPlayer = new MediaPlayer();
File path = android.os.Environment.getExternalStorageDirectory();
mediaPlayer.setDataSource(path + "urmp3filename");
See this related question: MediaPlayer issue between raw folder and sdcard on 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();
}
}
If the audio is in the local raw resource:
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
To play from a URI available locally in the system:
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();