Android music player application not opening - android

I am trying to make a simple application of a music player with simple ImageButtons for play and pause.
I tried doing it but from the emulator, at run-time, an error appears "unfortunately not able to open the appication."
I tried with only the code for play button and it worked but when the code for pause button is added the run-time error occurs. Can anyone tell me where I am going wrong?
Thank you.
public class Audio1Activity extends Activity {
private static final String TAG = "AudioDemo";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
private MediaPlayer player;
ImageButton playbtn,pausebtn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player= MediaPlayer.create(this , R.raw.a1);
playbtn=(ImageButton) this.findViewById(R.id.image_button1);
player.setLooping(false);
playbtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
demoPlay();
}
});
pausebtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
demoPause();
}
});
#Override
public void onPause() {
super.onPause();
player.pause();
}
private void demoPause(){
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, notPlaying);
}
private void demoPlay(){
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, isPlaying);
}
}

The error is you are not setting the pausebtn to be of the ImageButton widget.
Something like this should do it:
pausebtn = (ImageButton)findViewById(R.id.name_of_image_button_in_your_layout_xml);
if (pausebtn != null){
pausebtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
demoPause();
}
});
}

player.prepare();
try put this line before player.start();

Related

setOnCompletionListener is detecting the completion only for first time

setOnCompletionListener is detecting the completion of a song the first time only. In the code below song1 and song2 are played one after the other but the remaining songs are not being played.
I want to play the songs one by one and add some silence between songs.
MediaPlayer song0=new MediaPlayer();
int track = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
song0=MediaPlayer.create(this,R.raw.song1);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
function();
}
});
song0.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer song0) {
track++;
loadsong();
function();
}
});
}
void loadsong()
{
if(track==1) song0=MediaPlayer.create(this,R.raw.song2);
if(track==2) song0=MediaPlayer.create(this,R.raw.song3);
if(track==3) song0=MediaPlayer.create(this,R.raw.song4);
}**strong text**
void function(){
if(track<4) song0.start();
else
song0.stop();
}
The problem is that you create MediaPlayer object every time you need to play songs. So you need to set OnCompletionListener every time after creating MediaPlayer object for another song.
So you can change a few lines in your code to fix the issue.
MediaPlayer song0=new MediaPlayer();
int track = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
song0=MediaPlayer.create(this,R.raw.song1);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
function();
}
});
song0.setOnCompletionListener(m_CompletionListener);
}
void loadsong()
{
if(track==1) {
song0=MediaPlayer.create(this,R.raw.song2);
song0.setOnCompletionListener(m_CompletionListener);
}
if(track==2) {
song0=MediaPlayer.create(this,R.raw.song3);
song0.setOnCompletionListener(m_CompletionListener);
}
if(track==3) {
song0=MediaPlayer.create(this,R.raw.song4);
song0.setOnCompletionListener(m_CompletionListener);
}
}**strong text**
void function(){
if(track<4) song0.start();
else
song0.stop();
}
MediaPlayer.OnCompletionListener m_CompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer song0) {
track++;
loadsong();
function();
}
};
Another way to implement is to create only one MediaPlayer object and instead of creating MediaPlayer object everytime, call setDataSource function for playing other songs.
If you need this way more detail, i can make sample code also.
I hope it will help you!
Your onclickListener event only starting for once. If you want to play song one by one you have to create a loop or have to do it recursively. Here's a snippet where I used song0.setOnCompletionListener inside loadsong() and in the event recursively called loadsong() every time. Changed your loadsong() method a little bit. Here is the code:
public class MainActivity extends AppCompatActivity {
private Button play;
MediaPlayer song0 = new MediaPlayer();
int track = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadsong();
}
});
}
void loadsong() {
track++;
if (track == 1) {
song0 = MediaPlayer.create(this, R.raw.track1);
song0.start();
}else if (track == 2) {
song0 = MediaPlayer.create(this, R.raw.track2);
song0.start();
}else if (track == 3) {
song0 = MediaPlayer.create(this, R.raw.track3);
song0.start();
}else if (track > 3) {
song0.stop();
}
song0.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer song) {
song.stop();
loadsong();
}
});
}
}

Is this a good way to use MediaPlayer?

I think this is a decent way to use MediaPlayer for a Button or one time use. Am I right? Is the try block necessary? And what should I be trying to catch here? I'm really having a hard time finding a rock solid way to play a sound once.
// Button sound
private void playButtonSound() {
try{
final MediaPlayer startPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.sound);
startPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
startPlayer.release();
}
});
startPlayer.start();
} catch(Throwable t){}
}
I use it like that:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.tosse);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}

How to PLAY/STOP mediaplayer again?

I'm using a button "music" with 2 actions PLAY and STOP , when I click for the first time the music is played , then when I click again it's stopped. However when I click for the second time all actions PLAY/ STOP don't work .
public class Home extends Activity {
boolean isMediaOn=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton music=(ImageButton)findViewById(R.id.music);
final MediaPlayer sound=MediaPlayer.create(Accueil.this,R.raw.star);
music.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// play
if(isMediaOn==false)
{
System.out.println("PLAY");
sound.start();
music.setImageResource(R.drawable.music);
isMediaOn=true;
}
// stop
else
{
System.out.println("STOP");
if(sound.isPlaying()){
sound.reset();
sound.stop();
}
music.setImageResource(R.drawable.no_music);
isMediaOn=false;
}
}
});
Here is a screenshot of my logcat :
You're only allowed to call stop() when the player is in state STARTED, PREPARED, PAUSED or PLAYBACK_COMPLETE. Your reset() call is putting it back into IDLE state, causing stop() to fail.
You probably want to use pause(), as in sound.pause();
The pause() method pauses playback and maintains all other player states (such as file that's being played, location in file, etc).
In http://developer.android.com/reference/android/media/MediaPlayer.html#stop it is clearly stated that
'Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.'
public class Home extends Activity {
boolean isMediaOn=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton music=(ImageButton)findViewById(R.id.music);
final MediaPlayer sound=MediaPlayer.create(Accueil.this,R.raw.star);
music.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// play
if(isMediaOn==false)
{
System.out.println("PLAY");
try {
sound.prepare();
} catch (Exception e) {
Log.d(Settings.debug, e.toString());
}
sound.start();
music.setImageResource(R.drawable.music);
isMediaOn=true;
}
// stop
else
{
System.out.println("STOP");
if(sound.isPlaying()){
sound.reset();
sound.stop();
}
music.setImageResource(R.drawable.no_music);
isMediaOn=false;
}
}
});
Try this, hope this helps you.
final ImageButton music=(ImageButton)findViewById(R.id.music);
final MediaPlayer sound=MediaPlayer.create(Accueil.this,R.raw.star);
music.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(sound.isPlaying()){
sound.stop();
music.setImageResource(R.drawable.no_music);
} else {
sound.start();
music.setImageResource(R.drawable.music);
}
});

Android Media Player play/pause Button

In my project, I am playing music file in android media player by using the following code
MediaPlayer mPlayer = MediaPlayer.create(MyActivity.this, R.raw.myfile);
mPlayer.start();
the above is coded in the onclick of the play button.
I want to pause the playback by clicking the same button again.ie) single button for play/pause.
How shall i do this.
You could use simple if-check to handle the pausing. Try this:
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
Please try this::
final Button bPlay = (Button) findViewById(R.id.bPlay);
MediaPlayer song1 = MediaPlayer.create(tutorialFour.this, R.raw.fluet);
Button bStop = (Button) findViewById(R.id.bStop);
bPlay.setWidth(10);
song1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bPlay.setText("Play");
}
});
bPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
b = true;
if (bPlay.getText().equals("Play") && b == true) {
song1.start();
bPlay.setText("Pause");
b = false;
} else if (bPlay.getText().equals("Pause")) {
x = song1.getCurrentPosition();
song1.pause();
bPlay.setText("Resume");
Log.v("log", "" + x);
b = false;
} else if (bPlay.getText().equals("Resume") && b == true) {
song1.seekTo(x);
song1.start();
bPlay.setText("Pause");
b = false;
}
}
});
Inside the button click check for mediaPlayer.isPlaying(). This will return true if the media player is playing else false.
So now with this, flag value you can make a if statement and switch to play or pause like this,
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
} else {
mediaplayer.start();
}
}
});
Below code takes care of your play/pause button click event along with forward and backward buttons for forward and backward seek on the seekbar provided (which is synchronized with the media track). Currently it plays just ONE song. However, you can add to that. This is my first media player using mediaplayer class, so you might find it a bit primitive. However if you need you can also check out the VideoView examples. It's apparently easier with VideoView as the standard media console is already present in the form of pre-defined widgets. so that makes designing the player much easier.
package in.org.Test;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Toast;
public class Test12Activity extends Activity implements OnClickListener,Runnable {
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
private SeekBar seek;
MediaPlayer player = new MediaPlayer();
private ImageButton plus,minus;
ImageButton im;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton3);
player = MediaPlayer.create(this, R.raw.sound2);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton1);
seek = (SeekBar) findViewById(R.id.seekBar1);
seek.setVisibility(ProgressBar.VISIBLE);
seek.setProgress(0);
seek.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { int cu = player.getCurrentPosition(); player.seekTo(cu-5000); }});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {int cu = player.getCurrentPosition(); player.seekTo(cu+5000);}});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton1) {
if(player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.play);
}
else
{
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.pause);
}
}
}
#Override
public void run() {
int currentPosition= 0; String s;
int total = player.getDuration();
while (player!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek.setProgress(currentPosition);
}
}
}
MediaPlayer mpE = MediaPlayer.create(GuitarTuner.this, R.raw.test2 );
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mpE.isPlaying()) {
mpE.pause();
play.setBackgroundResource(R.drawable.play);
} else {
mpE.start();
play.setBackgroundResource(R.drawable.pause);
}
}
});
For pausing the Mediaplayer:
Mediaplayer.pause();
length = Mediaplayer.getCurrentPosition();
and for resuming the player from the position where it stopped lately is done by:
Mediaplayer.seekTo(length);
Mediaplayer.start();
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//the song was previously saved in the raw folder. The name of the song is mylife (it's an mp3 file)
final MediaPlayer mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.mylife);
// Play song
Button playButton = (Button) findViewById(R.id.play);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.start(); // no need to call prepare(); create() does that for you
}
});
// Pause song
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.pause();
}
});
// Stop song - when you stop a song, you can't play it again. First you need to prepare it.
Button stopButton = (Button) findViewById(R.id.stop);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.stop();
mMediaPlayer.prepareAsync();
}
});
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = button.getText().toString();
if (text.equals("play")){
mediaPlayer.start();
button.setText("pause"); //changing text
}
else if (text.equals("pause")){
mediaPlayer.pause();
button.setText("play"); //changing text
}
}
});
very simple solution. If mediaplayer is playing, display play button and pause the mediaplayer. If not playing, do the opposite.
playBtn.setOnClickListener(view -> {
//events on play buttons
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.play);
} else {
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.pause);
}
});

using only one button to play and pause a Mediaplayer in Android

I am new to Android, my requirement is to use only one button for playing and pause using media player class?
Once you have your MediaPlayer set up, I would just set up in your onCreate() and onResume() methods, a check to see if the MediaPlayer is currently playing (MediaPlayer's isPlaying() method should work for you), and if it is playing, set the button's image and click handler to change it to a pause button. If the MediaPlayer isn't playing, then set it to be a play button.
You'll also need to handle listening for events such as when the MediaPlayer stops (finishes playing the audio file), as well as inverting the button state when you press it (i.e. pressing play changes button to pause, and vice versa).
I would use 2 buttons and hide one of them:
public class MyActivity extends Activity implements View.OnClickListener {
Button playBtn;
Button pauseBtn;
public void onCreate() {
playBtn = (Button) findViewById(R.id.playButton);
pauseBtn = (Button) findViewById(R.id.pauseButton);
playBtn.setOnClickListener(this);
pauseBtn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.playButton:
// play music here
playBtn.setVisibility(Button.GONE);
pauseBtn.setVisibility(Button.VISIBLE);
break;
case R.id.pauseButton:
// pause music here
pauseBtn.setVisibility(Button.GONE);
playBtn.setVisibility(Button.VISIBLE);
break;
}
}
}
you can use a single Imagebutton and change the drawable image , in conjuction with a toggling boolean variable to check the state of the button (play/pause).
This is how I implemented it
ImageButton playButton;
private boolean playOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// some code here
playButton = (ImageButton)findViewById(R.id.btn_play);
//other specifications and your code
}
public void play(View view){
myplayfunction();
}
public void myplayfunction(){
if (playOn){
playOn=false;
playButton.setImageResource(R.drawable.icn_pause);
//your mediaplayer functions
}else{
playOn=true;
playButton.setImageResource(R.drawable.icn_play);
//pause the mediaplayer
}
}
Also, don't forget to toggle your imagebutton at the end, onCompletionListener() method of the mediaplayer
The following code worked for me. The value of the "playedLength" variable should also be initialize to zero, and set the "mediaPlaying" boolean value to false in the media player stop function to avoid errors.
public class MainActivity extends AppCompatActivity {
private Button btnPlay;
private MediaPlayer mPlayer;
private String mFileName = null;
private int playedLength; //variable for the CurrentPosition of audio when paused
private boolean mediaPlaying; // boolean variable for toggling play, pause and resume actions
// some custom codes for my app...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// some custom codes for my app.....
btnPlay = (Button) findViewById(R.id.button_play);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlaying){
mediaPlaying = false;
//pause the media player
mPlayer.pause();
playedLength = mPlayer.getCurrentPosition();
btnPlay.setBackgroundResource(R.mipmap.ic_pause_focused_background);
}else{
mediaPlaying = true;
if(mPlayer == null){
// create the media player
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
btnPlay.setBackgroundResource(R.mipmap.ic_play_focused_background);
} else
// resume playing
mPlayer.seekTo(playedLength);
mPlayer.start();
btnPlay.setBackgroundResource(R.mipmap.ic_play_focused_background);
}
}
});
}
final Button bPlay = (Button)findViewById(R.id.bPlay);
MediaPlayer song1 = MediaPlayer.create(tutorialFour.this, R.raw.fluet);
Button bStop = (Button)findViewById(R.id.bStop);
bPlay.setWidth(10);
song1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bPlay.setText("Play");
}
});
bPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
b=true;
if(bPlay.getText().equals("Play") && b==true)
{
song1.start();
bPlay.setText("Pause");
b=false;
}
else if(bPlay.getText().equals("Pause"))
{
x=song1.getCurrentPosition();
song1.pause();
bPlay.setText("Resume");
Log.v("log",""+x);
b=false;
}
else if(bPlay.getText().equals("Resume") && b==true)
{
song1.seekTo(x);
song1.start();
bPlay.setText("Pause");
b=false;
}
}
});
Button
android:id="#+id/buttonPlay"
android:onClick="Play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="160dp"
android:layout_marginTop="243dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="100dp"
android:text="#string/play"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
//-----------------------------------------------------------------------
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
boolean isPlaing = true;
Button buttonPlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = findViewById(R.id.buttonPlay);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.stuff);
}
public void Play(View view) {
if(isPlaing) {
mediaPlayer.start();
buttonPlay.setText("Pause");
isPlaing = false;
}else {
mediaPlayer.pause();
buttonPlay.setText("Play");
isPlaing = true;
}
}
}

Categories

Resources