Android - Looping Activity to Repeat MediaPlayer - android

I'm trying to create a soundboard for longer audio files and can't figure out how to stop an audio file and start it again without closing the activity. Let's say each audio file is one minute long. If I play the first audio file for 20 seconds and start the next audio file, the first stops playing and the second starts playing. However, if I click the first audio file again, the second stops playing and the first does not. I need help. This is driving me insane.
bAudio1 = (ImageButton) findViewById(R.id.bAudio1);
bAudio2 = (ImageButton) findViewById(R.id.bAudio2);
mpAudio1 = MediaPlayer.create(this, R.raw.audio1);
mpAudio2 = MediaPlayer.create(this, R.raw.audio2);
bAudio1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mpAudio1.isPlaying()) {
mpAudio1.stop();
} else {
if(mpAudio2.isPlaying()) { mpAudio2.stop(); }
mpAudio1.start();
}
}
});
bAudio2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mpAudio2.isPlaying()) {
mpAudio2.stop();
} else {
if(mpAudio1.isPlaying()) { mpAudio1.stop(); }
mpAudio2.start();
}
}
});

This worked for me:
public class ExampleActivity extends Activity implements OnClickListener {
private Button button1;
private Button button2;
private MediaPlayer mediaPlayer1;
private MediaPlayer mediaPlayer2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// play first audio clip and stop the second if playing
if (mediaPlayer2 != null && mediaPlayer2.isPlaying()) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = null;
}
mediaPlayer1 = MediaPlayer.create(this, R.raw.song1);
mediaPlayer1.start();
break;
case R.id.button2:
// play second audio clip and stop the first if playing
if (mediaPlayer1 != null && mediaPlayer1.isPlaying()) {
mediaPlayer1.stop();
mediaPlayer1.release();
mediaPlayer1 = null;
}
mediaPlayer2 = MediaPlayer.create(this, R.raw.song2);
mediaPlayer2.start();
break;
}
}
#Override
protected void onPause() {
super.onPause();
// stop the second if playing
if (mediaPlayer2 != null && mediaPlayer2.isPlaying()) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = null;
}
// stop the first if playing
if (mediaPlayer1 != null && mediaPlayer1.isPlaying()) {
mediaPlayer1.stop();
mediaPlayer1.release();
mediaPlayer1 = null;
}
}

Related

How to make ImageButton repeat a sound each time it's clicked

I am trying to get the Image Button to play a sound each time it's clicked. For example, if the sound is playing for few seconds and I press the button again it should start from the beginning. I managed to get the sound working but it's not repeating it. How can I get it to start over?
ImageButton bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
Try this:
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.bird);
}
mp.start();
} catch(Exception e) {
e.printStackTrace();
}
}
Use MediaPlayer.seekto() to seek to the start of the audio file.
ImageButton bt;
private MediaPlayer mp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()) {
mp.seekTo(0);
} else {
mp.start();
}
}
});
}

Making Sound Button stop after start

I need a button that will start when pressed and stop when pressed again. Otherwise I have overlapping sounds. Can any of you assist me with the code please? Below is what I currently have and can't get the button to stop when clicked again so currently it is just playing and stops when the sound is done causing sounds to overlap. Getting one to stop when another is pressed would also be ideal but I don't have a clue how to easily incorporate this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boardone);
Button one = (Button) findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(BoardoneActivity.this, R.raw.mouse_laughter);
mp.start();
}
});
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(BoardoneActivity.this, R.raw.evil_laugh);
mp.start();
}
});
Dont use two objects of Media Player. Bleow is the snippet of methods from my project. If any error let me know.
private MediaPlayerManager mRecordingPlayer = null;
private void initAudioPlayer(){
if(mRecordingPlayer == null){
mRecordingPlayer = new MediaPlayerManager();
}
}
private void playMusic(int position){
initAudioPlayer();
mRecordingPlayer.resetPlayer();
mRecordingPlayer.setupPlayback("your reasource");
mRecordingPlayer.startPlaying();
}
private void stopPlaying(){
initAudioPlayer();
if(mRecordingPlayer.isPlaying()){
mRecordingPlayer.pausePlaying();
}
}
#Override
public void onPause() {
clearAudioPlayer();
super.onPause();
}
private void clearAudioPlayer(){
if(mRecordingPlayer != null ){
mRecordingPlayer.resetPlayer();
}
}
#Override
public void onClick(View view) {
boolean on = ((ToggleButton) view).isChecked();
if(on){
playMusic("play music");
((ToggleButton) view).setChecked(true);
}else{
stopPlaying();
}
}
Try it with below code.
mPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
mPlayPause.setText("Play");
}
} else {
if (mp != null) {
mp.start();
mPlayPause.setText("Pause");
}
}
}
});

I have following piece of code to stop media player

While pressing start button it starts playing the mp3 file, but it doesn't stop while pressing Stop button, I have been through few examples but couldn't find the exact solution
public Button play;
public Button stop;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id.played);
stop = (Button)findViewById(R.id.stopped);
play.setOnClickListener(this);
stop.setOnClickListener(this);
}
public void onClick(View v) </br>
{
mp = MediaPlayer.create(this,R.raw.you);
if(v==play && !mp.isPlaying()){
mp.start();
}
//below part of code executes but doesn't stop the player
else if (v==stop){
mp.stop();
mp.release();
}
}
Do like this :
public void onClick(View v) {
switch (v.getId()) {
case R.id.played:
if(mp==null || !mp.isPlaying()){
mp = MediaPlayer.create(this,R.raw.you);
mp.start();
}
break;
case R.id.stopped:
if(mp!=null && mp.isPlaying()){
mp.stop();
mp.release();
}
break
default:
break;
}
}
mp = MediaPlayer.create(this,R.raw.you);
create returns a new instance every time you call it. So you are invoking stop() on an instance of mp different from the one upon you called start(). You should call create once, in the onCreate for instance

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