I have a mp3 file in my android mobile, lets it's a xyz.mp3 somewhere in my sdcard.
How to play it through my application?
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();
#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
public class MainActivity extends Activity implements OnClickListener {
Button play;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
play=(Button)findViewById(R.id.button1);
play.setOnClickListener(this);
}
#Override
public void onClick(View arg0)
{
mp=MediaPlayer.create(getApplicationContext(),R.raw.song);// the song is a filename which i have pasted inside a folder **raw** created under the **res** folder.//
mp.start();
}
#Override
protected void onDestroy() {
mp.release();
super.onDestroy();
}
}
The replay from https://stackoverflow.com/users/726863/lalit-poptani is great one, it worked the first time, but as I used to have the full path of the file, I did it this way
public void audioPlayer(String path){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(path );
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Credit to http://www.helloandroid.com/tutorials/how-play-video-and-audio-android
Related
some audio file url not playing in mediaplayer
here my code
mediaPlayer = new MediaPlayer();
if (mediaPlayer != null) {
try {
String audioUrl = Constants.AudioLink.toString().replace(" ", "%20");
mediaPlayer.setDataSource(audioUrl);
mediaPlayer.prepareAsync();
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
Progressdialogs.getInstance().closeDialog();
Toast.makeText(AudioPlayActivity.this, "Failed to load audio", Toast.LENGTH_SHORT).show();
return false;
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Progressdialogs.getInstance().closeDialog();
finalTime = mediaPlayer.getDuration();
seekbar.setMax((int) finalTime);
seekbar.setClickable(false);
play();
duration.setVisibility(View.VISIBLE);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
I noticed that small audio files easily played but large audio file not playing. i also try FFmpegMediaPlayer library intead of MediaPlayer then large audio file played but my apk file size increase to 32 MB. so i can't use FFmpegMediaPlayer for play audio through url. Please suggest me best library or native code for play large audio file as live stream.
Thanks in advance
i use following library
compile 'com.devbrackets.android:exomedia:3.1.1'
now large file playing perfectly.
Use
import com.devbrackets.android.exomedia.EMAudioPlayer;
private EMAudioPlayer mediaPlayer;
MediaPlayer doesn't play my MP3
I am using the following code to play a (random) MP3-song from the internet, but unfortunately is isn't working. I don't hear anything, but I don't know what I am doing wrong.
public void playAudio() throws Exception
{
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
// mediaPlayer.release();
mediaPlayer.setDataSource("http://yvolinssen.nl/recit.mp3");
mediaPlayer.prepare();
mediaPlayer.start();
}
I also tried to put the
MediaPlayer mediaPlayer;
In the constructer, but that isn't working either. The following function calls my PlayAudio function:
this.playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
UserPanel.this.activity.playAudio();
} catch (Exception e) {
e.printStackTrace();
}
}
});
I have an app where I want, as soon as it starts, a little background music (opa gangam style!) to be played (from the sd card). I use the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = new MediaPlayer();
String filePath = Environment.getExternalStorageDirectory().getPath() + "/mymusic/gangamstyle.mp3";
try {
mp.setDataSource(filePath);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
But when I test it, no music is played. I see everything is ok however. What could I do wrong? Thanks a lot
You have to use setOnPreparedListener in order to know when the media player is ready to play:
MediaPlayer player = new MediaPlayer();
player.setDataSource(filePath);
player.setVolume(100, 100);
player.setLooping(false);
player.setOnPreparedListener(new OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
});
player.prepare();
There is some problem in your file path. Media player gives this kind of error when the file path is not correct. So, Please check your file path and then try it.
I m making an app which is supposed to play a few sounds with the mediaPlayer.
This is the code i use :
String[] name = {"sonar_slow","sonar_medium","sonar_fast"};
String link = "/res/raw/" + name[state-1] + ".mp3";
try {
player.setDataSource(link);
player.prepare();
player.start();
} catch(Exception e) {
e.printStackTrace();
}
I also tried this :
if(state==1){
player.create(this, R.raw.sonar_slow);
}else if(state==2){
player.create(this, R.raw.sonar_medium);
}else if(state==3){
player.create(this, R.raw.sonar_fast);
}
player.start();
But none of the above is working. My app is not crashing but the sound is not playing.
Any ideas ?
There are two problems.
Problem 1
You cannot reference resources inside your projects /res/raw directory in this fashion. The file "/res/raw/sonar_slow.mp3" in your project directory is not stored in "/res/raw/sonar_slow.mp3" in your apk. Instead of the following:
MediaPlayer mp = MediaPlayer.create(this);
mp.setSource("sonar_slow");
You need to use
MediaPlayer mp = MediaPlayer.create(this, R.raw.sonar_slow);
Problem 2
The following is wrong: it calls a static method that does not modify the player.
player.create(this, R.raw.sonar_slow);
You should instead call
player = MediaPlayer.create(this, R.raw.sonar_slow);
Full solution
Below is a reusable AudioPlayer class that encapsulates MediaPlayer. This is slightly modified from "Android Programming: The Big Nerd Ranch Guide". It makes sure to remember to clean up resources
package com.example.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer {
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public void play(Context c, int rid) {
stop();
mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
}
How to play a file with MediaPlayer:
MediaPlayer mp = MediaPlayer.create(this, R.raw.mysound); // sound is inside res/raw/mysound
mp.start();
This is a simple example of how to play a sound with the Android MediaPlayer.
You have two buttons hat each play a different sound. The selecting of the sound and actually playing it is done in the manageSound() method. The sounds "hello", "goodbye" and "what" are in the res/raw directory:
MediaPlayer mp = null;
String hello = "Hello!";
String goodbye = "GoodBye!";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button buttonHello = (Button) findViewById(R.id.idHello);
buttonHello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
managerOfSound(hello);
} // END onClick()
}); // END buttonHello
final Button buttonGoodBye = (Button) findViewById(R.id.idGoodBye);
buttonGoodBye.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
managerOfSound(goodbye);
} // END onClick()
}); // END buttonGoodBye
} // END onCreate()
protected void manageSound(String theText) {
if (mp != null) {
mp.reset();
mp.release();
}
if (theText.equals(hello))
mp = MediaPlayer.create(this, R.raw.hello);
else if (theText.equals(goodbye))
mp = MediaPlayer.create(this, R.raw.goodbye);
else
mp = MediaPlayer.create(this, R.raw.what);
mp.start();
}
Taken from here: http://www.badprog.com/android-mediaplayer-example-of-playing-sounds
Furthermore, I would strongly recommend using SoundPool instead of MediaPlayer, for better Performance and usability.
http://developer.android.com/reference/android/media/SoundPool.html
Please also check if your sound is muted - I know this sounds stupid, but it happens to the best of us ;)
You need to do it like this :
try{
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
Make sure your only playing when the file has finished preparing.
I have a very simple mediaplayer that play background. It calls file from the apk, but I want it to play from any directory like as music or sdcard.
Here is my code:
private MediaPlayer mpintro;
.
.
mpintro = MediaPlayer.create(this, R.raw.intro);
mpintro.setLooping(true);
mpintro.start();
It works like this:
mpintro = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/intro.mp3"));
mpintro.setLooping(true);
mpintro.start();
It did not work properly as string filepath...
String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start()
and this play from raw folder.
int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
mediaPlayer.prepare();
mediaPlayer.start();
mycontext=application.this. use.
Here is the code to set up a MediaPlayer to play off of the SD card:
String PATH_TO_FILE = "/sdcard/music.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();
mediaPlayer.start()
You can see the full example here. Let me know if you have any problems.
Use the code below it worked for me.
MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/mnt/sdcard/yourdirectory/youraudiofile.mp3");
mp.prepare();
mp.start();
I use this class for Audio play. If your audio location is raw
folder.
Call method for play:
new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
.getDetail().get(0).getAudio(),"raw", getPackageName()));
AudioPlayer.java class:
public class AudioPlayer {
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
// mothod for raw folder (R.raw.fileName)
public void play(Context context, int rid){
stop();
mMediaPlayer = MediaPlayer.create(context, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
// mothod for other folder
public void play(Context context, String name) {
stop();
//mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
}
2020 - NOV
This worked for me:
final File file = new File(getFilesDir(), "test.wav");//OR path to existing file
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));
mediaPlayer.start();
In Kotlin:
1) The file is in a resource folder :
var nowLesson =resources.getIdentifier("test.mp3", "raw", packageName)
mediaPlayer = MediaPlayer.create(applicationContext, nowLesson)
mediaPlayer.start()
2) The file is in a Path (file path)
val file = File(
this.getDir("Music", MODE_PRIVATE),
"/t.mp3"
)
mediaPlayer = MediaPlayer.create(this,Uri.fromFile(file ))
mediaPlayer.start()