Mediaplayer plays twice - android

I have a media player but when another file is selected it continues to play the old file and new one so it is playing two files at once here is my onCreate method
private MediaPlayer mediaplayer = new MediaPlayer();
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.songplaying);
// Getting Our Extras From Intent
Bundle names = getIntent().getExtras();
// Getting Specific Data
path = names.getString("pathkeyword");
//Start Player
try {
playAudio(path);
} catch (Exception e) {
e.printStackTrace();
}
and this is the method that plays the audio
private void playAudio(String url) throws Exception{
mediaplayer.release();
mediaplayer.setDataSource(url);
mediaplayer.prepare();
mediaplayer.start();

When you are start to play the song ,check it is playing or not and stop it if it is currently playing.
if(player.isPlaying())
{
mediaplayer.stop();
}
mediaplayer.reset();
mediaplayer.setDataSource(url);
mediaplayer.prepare();
mediaplayer.start();
no need to release the player.player.release() used only when player no longer needed .
And you have to use stop() and release() methods whenever activity destroys.Otherwise so many players are running in background.

Try to add this to oncreate method so you will be able to prevent the new creation of audio
Mediaplayer M = Mediaplayer.create(this,R.row.audio file)
and make a new function like
void my function {
// call it here
m.start();
}

Related

Android media player delay in prepare()

I have my code which plays music from the internet. My problem is it has a few delay and causes lag after clicking the button.
I have tried to use the prepareAsync() but no luck. Can anyone please let me know the issue.
#Override
public void onClick(View v) {
if (v.getId() == R.id.ButtonTestPlayPause) {
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource(editTextSongURL.getText().toString()); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.button_pause);
} else {
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.button_play);
}
primarySeekBarProgressUpdater();
}
}

Can't play MediaPlayer onCreate

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.

Playing Sound from server using Media Player

I'm trying to play a sound in android using media player with no success,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "https://dl.dropboxusercontent.com/u/108022472/5041046.mp3";
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.prepareAsync();
}
I'm getting this from logcat:
prepareAsync called in state 1
Anything wrong in the code above?
You're already prepared by calling prepare(). There's no need to call prepareAsync() if you already called prepare(). Drop one of those two calls.

Play a sound from res/raw

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.

how to play audio file in android

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

Categories

Resources