This is the code in my main Activity:
private void initControls()
{
streamButton = (Button) findViewById(R.id.button_stream);
streamButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
loading = (ProgressBar) findViewById(R.id.progressBar1);
Toast
.makeText(
MyActivity.this,
"The following stream is about to start" + station,
Toast.LENGTH_LONG).show();
player.playAudioFile(urlstring2);
streamButton.setEnabled(false);
notificate();
}
});
}
And here is the code in witch i start the mediaplayer itself:
public class player extends MyMainActivity{
static MediaPlayer player;
private static final String TAG = player.class.getSimpleName();
public static void playAudioFile(String urlstring2) {
player = new MediaPlayer();
try {
player.setDataSource(urlstring2);
loading.setVisibility(View.VISIBLE);
player.prepareAsync();
//player.start();
} catch (Throwable thr) {
Log.e(TAG, "could not play audio", thr);
loading.setVisibility(View.INVISIBLE);
}
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
loading.setVisibility(View.INVISIBLE);
}
});
}
public static void releasePlayer() {
if (player != null) {
// Player-Ressourcen freigeben
player.release();
player = null;
}
}
}
What I want to do is to show the progressBar (the cicling one) when the user presses the "play" Button, and I need it to disapear when the mediaplayer starts to play.
atm I just get the circle to show after the player has startet to play and never disapear ...
Edit: I got it to work.
I did initiate the player like this: player.prepare(); insteas of player.prepareAsync();
So the progressbar was shown for a view milliseconds.
Try this out.
Start the Progress Bar in the button click here like this,
streamButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
ProgressDialog progressDialog=null;
progressDialog=ProgressDialog.show(context, "", "Playing...");
Toast
.makeText(
MyActivity.this,
"The following stream is about to start" + station,
Toast.LENGTH_LONG).show();
player.playAudioFile(urlstring2);
streamButton.setEnabled(false);
notificate();
}
});
And you have to override the media player's on Prepared listener, so that you can stop the progress bar within it like this,
Player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
progressDialog.cancel();
}
});
By this you can achieve to show Progress until your Mediaplayer starts to play the file.
Came back to finally mark this Question as solved, so I copied what I edited into my question previously.
I got it to work. I did initiate the player like this:
player.prepare(); insteas of player.prepareAsync(); So the progressbar
was shown for a view milliseconds.
add the code to hide your ProgressBar after this line:
player.start();
And also in your catch block. That should make it go away once the player is either playing, or failing to play.
If you add the code that you are using to show the ProgressBar now I can help you with how to hide it also.
Related
I am trying to build a small app which plays a sound when we click on the button. But I am not able to play the sound. Don't know what the problem is. Please help me on this. Below is the code.
public class MainActivity extends AppCompatActivity {
private Button button;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
button = (Button)findViewById(R.id.mediaButtonId);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}
Note:-Sorry guys,I thought that the problem is with my code but the app is running perfectly fine on my phone,so its the problem with my genymotion emulator.Can anyone please suggest me the solution for this.By the way,I am using Mac OSX.
The MediaPlayer has its own lifecycle. You can't just create the instance and then start to play. First you have to prepare it and then play it.
You can prepare your mediaplayer either sync or asynchronously.
Something along the lines of:
MediaPlayer mediaPlayer= new MediaPlayer();
mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.song);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
Or, if you want to do it synchronously
MediaPlayer mediaPlayer= new MediaPlayer();
mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.song);
try {
mediaPlayer.prepare();
} catch (IOException e){
}
mediaPlayer.start();
Just make sure you prepare it before you play it.
Media Player lifecycle: https://developer.android.com/reference/android/media/MediaPlayer.html
You need to make sure the media player is ready before you can play it, so you set the onPreparedListener to handle this for you, like so:
MediaPlayer mp = new MediaPlayer();
mp = MediaPlayer.create(getApplicationContext(),R.raw.song);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
}
});
button = (Button)findViewById(R.id.mediaButtonId);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.prepareAsync();
}
});
There will be a slight delay from when you press the button to the sound playing this way. Another way to do it could be to disable the button until the media player has prepared and then in the onclick of the button you could just call mp.start(); when the button has been enabled.
I've created this simple soundboard app which plays a sound on click. I've also setup so that the text changes when the button is hit but is there anyway for the text to change back to its original when the sound file is finished playing
Thanks in advance!
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button aussi = (Button) findViewById(R.id.aussi);
aussi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(aussi.getText().toString().equals("Australian")){
try{
}catch (Exception e){
e.printStackTrace();
}
aussi.setText("Jay");
mediaPlayer = MediaPlayer.create(MainActivity.this,
R.raw.aussi);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer play) {
// TODO Auto-generated method stub
play.release();
}
});
}
}
});
You got the solution by yourself, the completion listener tells you when the sound finishes playing. so :
#Override
public void onCompletion(MediaPlayer play) {
play.release();
// Now you can set you text
aussi.setText("your original text");
}
});
I have a list of players (ListView). Each item is have two buttons "start" and "stop". When I click on "start" color "Start" button change red and begins to move seekbar. When click on the "stop" button color "start" start is black and seekbar progress becomes zero. when the song ends with the color button "start" also becomes black and seekbar progress becomes zero.
holder.start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
releaseMP();
startPlayProgressUpdater(holder.seekBar, holder.start);
try {
mediaPlayer = new MediaPlayer();
global_position = position;
mediaPlayer.setDataSource(recordBeans.get(global_position).getFile());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
holder.seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
recordBeans.get(global_position).setPlay(true);
holder.start.setTextColor(Color.RED);
startPlayProgressUpdater(holder.seekBar, holder.start);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
releaseMP();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
This is implemented in this method:
public void startPlayProgressUpdater(final SeekBar seekBar, final Button start) {
if (mediaPlayer != null) {
recordBeans.get(global_position).setSeekPos(mediaPlayer.getCurrentPosition());
if ((Integer) seekBar.getTag() == global_position) {
seekBar.setProgress(recordBeans.get(global_position).getSeekPos());
}
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater(seekBar, start);
}
};
handler.postDelayed(notification, 1000);
} else {
recordBeans.get(global_position).setPlay(false);
start.setTextColor(Color.BLACK);
recordBeans.get(global_position).setSeekPos(0);
seekBar.setProgress(0);
}
}
When I click the "stop" or the song ends, the player becomes the NULL and color button again changes. it is implemented in all of these methods:
holder.stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((Integer) v.getTag() == global_position && mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
});
and
private void releaseMP() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want the same functionality if I worked while playing the song click on the "start" another song. ie a new song starts playing, the color buttons "start" becomes A red color and previous button "start" again black.
for this I when you click on "start" call methods:
releaseMP();
startPlayProgressUpdater(holder.seekBar, holder.start);
and the method works but the data is not cleared. but if I click on "Stop" then the data of all previous songs cleared. what I'm doing wrong?
I think you meant to call reset(), not release() in the stop button OnClick. Try to call release() in your main container OnStop()
reset()
This method resets the media player
release()
This method releases any resource attached with MediaPlayer object
There is a problem in the following media player that plays the audio stream when you press play if the stream is not available there is no any response from the program, How can I solve this issue, try to make progress dialog, but the solution does not work, maybe I did something wrong, but when you click on the progress bar appears first and then immediately disappears without waiting to start playback of music.
setDataSource filed in advance a broken link, nothing has changed.
Code media player with progress dialog:
private class ProgressTask extends AsyncTask <Void,Void,Void>{
#Override
protected void onPreExecute(){
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... arg0) {
preload();
return null;
}
#Override
protected void onPostExecute(Void result) {
MPplay();
progressbar.setVisibility(View.GONE);
}
}
public void preload() {
releaseMP();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
if(pdaStream.isChecked()){
Main_stream = "http://145.255.233.204:58000/radio_pda";
}else{
Main_stream = "http://145.255.233.204:58000/radio";
}
mediaPlayer.setDataSource(Main_stream);
} catch (IOException e) {
e.printStackTrace();
}
Log.d(LOG_TAG, "prepareAsync");
mediaPlayer.prepareAsync();;
}
public void MPplay(){
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
If you want to see when a video is ready for playback, use this callback. http://developer.android.com/reference/android/media/MediaPlayer.OnPreparedListener.html
onPrepared(MediaPlayer mp)
//Called when the media file is ready for playback.
If you would like to see when a video is 100% buffered, use this callback: http://developer.android.com/reference/android/media/MediaPlayer.OnBufferingUpdateListener.html
public abstract void onBufferingUpdate (MediaPlayer mp, int percent)
I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second time. That part works fine now here is the problem, when I click again on button to play sound again, it doesn't play it, Media player is completely stopped. I was looking on forums but I can't seem to find an answer that could help me.
Here is my Activity:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
final MediaPlayer mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset();
}
else {
mpButtonClick1.start();
}
}
});
When I try to write mpButtonClick1.prepare(); I get error Unhandled Exception Type IOE exception
Try to use pause instead of stop.
Reason: if you pause the MediaPlayer, then you can resume it later. However, if you use stop, almost any other method won't work and you will have to prepare the MediaPlayer again (or create a new one).
More info: here and here
PS: don't forget to release the memory when you finish using the resources.
Try this:
You should use only one mediaplayer object
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Change your class with below code:
remove reset();.
init well all components:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
}
else {
mpButtonClick1.start();
}
}
});
You're calling mpButtonClick1.reset() after mpButtonClick1.stop() - don't do that:
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset(); //<--------- calling reset(), remove this line
}
The docs for reset() say:
Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
Remove mpButtonClick1.reset() and it should work.
Keep in mind that MediaPlayer works as a state machine, which means that if you call methods in the wrong order, you'll get problems. Please read about MediaPlayer here and here.
Hey please use following
for stop -> media player
mp.seekTo(0);
mp.pause();
again for start just call
mp.start();
In my experience when I need to play multiple times and I may need to stop one play to start another play, (like in the case of multiple buttons), I just create another player, making sure that I release the resources for the previous one. To stop just use
mediaPlayer.stop();
But for play use something like this (adapt the logging to your specific needs) to create/recreate your player:
private boolean createMediaPlayer()
{
if (mediaPlayer!=null)
{
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer=null;
}
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setVolume(1f, 1f);
try
{
mediaPlayer.setAudioStreamType(Interop.PRIMARY_STREAM);
mediaPlayer.setDataSource(m_soundFile);
mediaPlayer.prepare();
return true;
// Interop.logDebug(TAG + "-loadAudio: SUCCESS" + m_soundFile);
} catch (Exception e)
{
Interop.logError(TAG + "-LoadAudio for Clic Sound: audioPlayer prepare failed for current file: " + m_soundFile);
Interop.logError(TAG + "-Exception: " , e);
return false;
}
}
and than use
if (createMediaPlayer())
mediaPlayer.start();
this will ensure proper release of the resources used by the media player.
A simple solution is to Use pause instead of stop and the seek to the beginning of the song.
I know that this question is quite old but recently while learning Android, I also got stuck at this point and found a very simple solution which I'd like to share with everyone.
Instead of trying to stop or reset the media, you can just seek back to the starting position.
mediaPlayer.seekTo(0);
For reference, I am also posting my code below:
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
public void play(View view) {
mp.start();
}
public void pause(View view) {
mp.pause();
}
public void stop(View view) {
// this seeks to the beginning of the file
mp.seekTo(0);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.sample_audio);
}
}