Media Player Button Is Not Restarting - android

I wanna make "Play/Stop" button. When button "Play" is clicked, the song must be played and its text should be converted into "Stop" and when "Stop" is clicked, the button text should be changed into "Play" again and song should start again to play from the beginning.
import android.media.MediaPlayer;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button btn_playStop;
private MediaPlayer mediaPlayer;
private boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Play Music");
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.zara_sa);
btn_playStop = (Button)findViewById(R.id.btn_play_stop);
btn_playStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() && flag==true){
stopSong();
}
else if (flag == false){
playSong();
}
}
});
}
public void playSong(){
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}
public void stopSong() {
mediaPlayer.stop();
btn_playStop.setText("Play");
flag = false;
}
}

You must call mediaPlayer.prepare(); if you called mediaPlayer.stop(); so in the first time you can just call mediaPlayer.start(); but in the next times you should call mediaPlayer.prepare(); before mediaPlayer.start();
public void playSong(){
try {
mediaPlayer.prepare();
} catch (IOException e) {
}
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}

Related

Android MP3 Player, play/pause button not working

I'm following an Udemy class on making a MP3 player like Spotify. I'm new to Android studio, and know/understand very little. The class is a bit older, and uses an older version of Android Studio from 2 years ago, so this might be part of the problem. I can hear the MP3 when I first start debugging, and the button will also change from play to pause, however, it is unresponsive to any clicking. I hear the sound it's been clicked, but it never changes status or pauses the audio. Thank you for the assistance, it's greatly appreciated!
***************** Main Activity.java ************************
package live.regionradio.regionradio;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.media.MediaPlayer;
import java.io.IOException;
import android.media.AudioManager;
public class MainActivity extends AppCompatActivity {
static FloatingActionButton btnPlayPause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnPlayPause = (FloatingActionButton) findViewById(R.id.fab);
btnPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
String url = "https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3";
if (Player.player == null)
new Player();
Player.player.playStream(url);
}
public static void flipPlayPauseButton (boolean isPlaying) {
if (isPlaying) {
btnPlayPause.setImageResource(android.R.drawable.ic_media_pause);
}
else {
btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
***************** Player.java ************************
package live.regionradio.regionradio;
import android.media.MediaPlayer;
import android.media.AudioManager;
import android.util.Log;
import java.io.IOException;
public class Player {
MediaPlayer mediaPlayer = new MediaPlayer();
public static Player player;
String url = "";
public Player() {
this.player = this;
}
public void playStream(String url) {
if (mediaPlayer != null) {
try {
mediaPlayer.stop();
} catch (Exception e) {
}
mediaPlayer = null;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
private MediaPlayer mp;
#Override
public void onPrepared(MediaPlayer mp) {
this.mp = mp;
playPlayer();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
private MediaPlayer mp;
#Override
public void onCompletion(MediaPlayer mp) {
this.mp = mp;
MainActivity.flipPlayPauseButton(false);
}
});
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
public void pausePlayer () {
try {
mediaPlayer.pause();
MainActivity.flipPlayPauseButton(false);
}
catch (Exception e) {
Log.d("EXCEPTION", "Failed to pause media player.");
}
}
public void playPlayer () {
try {
mediaPlayer.start();
MainActivity.flipPlayPauseButton(true);
}
catch (Exception e) {
Log.d("EXCEPTION", "Failed to play media player.");
}
}
public void togglePlayer () {
try {
if (mediaPlayer.isPlaying())
pausePlayer();
else
playPlayer();
}
catch (Exception e){
Log.d("Exception", "failed to toggle media player.");
}
}
}
public void onClick(View view) {
}
I believe this is exactly what happens after you click the button, namely - nothing. You should put something inside that function. You override the onClick function and leave it empty, so anything you would want to happen after clicking, you should put inside it.
Your "togglePlayer()" is never used, perhaps that's what you should put in the listener.

How To play radio app in background and show Widget on notification bar?

Considering this code:
package com.radio.radiostar;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import java.io.IOException;
public class MainActivity extends Activity implements OnClickListener {
private final static String RADIO_STATION_URL = "http://178.32.137.180:8665/stream";
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
};
I want to enable the background play, with a widget on notification bar like "apollo" or any other media player (with only play/pause button and the "x" to close streaming and background).
Can you help me, writing the code that I must use, and in which part of code?
Thanks in advance.
Fabio.
EDIT: I have deleted
if (player.isPlaying()) {
player.p();
From
#Override
protected void onPause() {
super.onPause();
}
And now works in background u.u
I only need to show the widget on notification bar :)
You want to play the stream while the app is minimized? Then you have to user the Service. You should move your code to the service. And you will be able to handle notification bar from the service as well.
When you do this, you will probably ask yourself "how can I now update the UI since the player is handled in the service". The answer to this is usage of BroadcastService where your Service will broadcast all important data (like timer ticks while stream is active) and your Activity has to catch those data and use it to fill its own UI.
Since the code for what I described here is huge, you should try implementing a service and broadcast logic first, and if you are stuck, come back here with a concrete question.

Double sound android

package project.kalmas;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
public class one extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
}
public void onclick2(View view)
{
Intent i=new Intent("project.two");
startActivity(i);
}
public void onclick3(View view)
{
MediaPlayer mp= MediaPlayer.create(this,R.raw.one);
if(mp.isPlaying()){
mp.stop();
} else {
mp.start();
}
}
}
When i click button it play sound then again i click button to stop it wont stop and play sound again which results in double sound playing at one time.Please help
You are creating a new MediaPlayer with every click, instead of keeping a reference to the first one. The MediaPlayer that is playing the sound is different than the MediaPlayer that you are calling isPlaying() on. You need to turn the mp variable into a field so you can keep a reference to it.
I imagine something like this would work:
public class one extends Activity {
MediaPlayer mp;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
mp = MediaPlayer.create(this,R.raw.one);
}
public void onclick2(View view)
{
Intent i=new Intent("project.two");
startActivity(i);
}
public void onclick3(View view)
{
if(mp.isPlaying()){
mp.stop();
} else {
mp.start();
}
}
}

android mediaplayer double play

I have a problem. This is stream player it is playing fine but when I start play, change app and again start player app the stop button is disabled.
If I pressing play again - it start plaing double music and I cannot stop first stream playing.
In short: I need one app and one sound and possibility to stop sound (without double playing)
import com.erkutaras.media.audio.url.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://play.org.ua:8000/";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}
In your OnClick() method add if:
if (mediaPlayer.isPlaying())
{
//mediaPlayer.pause; //or what you want instead double play
}
else
{
//your code
}

MediaPlayer android doesnt play

i use these lines to play some audio file with mediaplayer, both on a service and in an activity, yet there is no sound on my device, what could be the reason? and what should i try to do to understand whats wrong and finally fix that?
MediaPlayer mp = MediaPlayer.create(this, R.raw.alert);
mp.start();
Intent viewMediaIntent = new Intent();
viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(objectFilePath);
viewMediaIntent.setDataAndType(Uri.fromFile(file), "audio/*");
viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(viewMediaIntent);
http://developer.android.com/reference/android/media/MediaPlayer.html
Check out the state diagram in the MediaPlayer docs.
After you've created the MediaPlayer it is in the Idle state. As you can see, you need to initialize and prepare it before you call start().
Check the following code, it works fine for me. I hope it will work for you also.....Dont forget to add Audio PlayBack permission in android Manifest File
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://android.erkutaras.com/media/audio.mp3";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}

Categories

Resources