Play and Stop in One button - android

i'm newbie, i'm tried to make play audio play and stop for 1 button only, but i'm in trouble now.
if i touch a button when audio is playing, it doesn't stop, even playing audio again and make a double sound.
here's my code
public class ProjectisengActivity extends Activity{
ImageButton mainkan;
MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
i'm create for android 3.0 (HoneyComb)

try below code in go function....
public void go() {
if(mp == null) {
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
}
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
}

It is simple, you should follow these steps to achieve this.
In your test2.xml create two buttons name start and stop.
Set the android:visibility attribute gone of stop button in xml file.
Now in your activity get the id of these two buttons and write the code for
starting and stopping of media player.
Set the visibility attribute gone on start click and visible of stop button,
follow its opposite on stop click.

I think you have wrong this line :
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
You create new instance every time user clicks the button, so it's never playing and starts again. Put this line into onCreate rather than go()

Try also this,
public class MainActivity extends Activity {
MediaPlayer mPlayer;
int flag = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (flag == 0) {
Log.v("Inside if", "Success" + "");
mPlayer = MediaPlayer.create(getApplicationContext(),
R.raw.sample);
mPlayer.start();
flag++;
} else {
Log.v("Inside else", "Success" + "");
mPlayer.stop();
mPlayer.release();
flag = 0;
}
}
});
}
}

Related

How to code play stop button on android studio

I need some advice about the code below. I'm trying to create a simple apps that when people click play button, then the music will start playing, and when people click the stop button, the music will stop playing. I'm using a single button for this two task start and stop.
I already test on android simulator, this start and stop button are working properly as I wanted to. But the problem occurred when I build an APK file and play it on a device. The stop button cannot work as I wanted to. If I press the stop button, the music will restart the playing from the beginning.
Any ideas about this problem? Thank you.
btn_playstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btn_playstop.isPressed()) {
if (player.isPlaying()) {
player.stop();
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.seekTo(0);
btn_playstop.setBackgroundResource(R.drawable.play);
}
else {
player.start();
btn_playstop.setBackgroundResource(R.drawable.stop);
}
}
}
});
To achieve the play/stop button, do it this way.
btn_playstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (player != null && player.isPlaying()) {
player.stop();
player.release();
player = null;
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.seekTo(0); //<---- This is to resume the player from a specified position. It is helpful for a pause button. You can remove it for a stop button.
btn_playstop.setBackgroundResource(R.drawable.play);
}
else {
player.start();
btn_playstop.setBackgroundResource(R.drawable.stop);
}
}
});
You don't have to call the seekTo(Length) method for a stop button as it is meant for resuming the player from a specified position. Also if (btn_playstop.isPressed()) is unnecessary as you have already called the button using setOnClickListener.
imabutton=findViewById(R.id.imgbutton);
imabutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (imabutton.getTag().toString().contains("not_playing")){
if (mediaPlayer!=null)mediaPlayer.release();
mediaPlayer=MediaPlayer.create(MainActivity.this,R.raw.music1);
mediaPlayer.start();
imabutton.setImageResource(R.drawable.stop);
imabutton.setTag("playing");
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
imabutton.setTag("not_playing");
imabutton.setImageResource(R.drawable.play);
}
});
}else {
mediaPlayer.release();
imabutton.setImageResource(R.drawable.play);
imabutton.setTag("not_playing");
}
}
});

one button music play/stop with playing in startup of activity android

I have an app with one button for play/stop music . when I run the app , music stops in start up of that . But I want when I run the app that music plays automatically and if I click the button , music stops . I searched the site but I cant find the answer .Please help me my friends.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
You can follow this:
if (mp == null) {
mp = MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
}
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
you can use toggle button like below
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
Call go() method in your activity oncreate method.
Its play automatically on activity start when you button clicked its again call the same method so the condition is palying so its stopped.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
go();
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);

Android mediaPlayer only plays file once

I'm trying to create an app that play a certain audio file, that was previously recorded, when I press a button or shake my phone. Here is my code.
public class Reproduzir extends Activity implements SensorEventListener{
MediaPlayer player = new MediaPlayer();
SensorManager sensor;
#Override
protected void onCreate(Bundle savedInstanceState ){
super.onCreate(savedInstanceState);
sensor= (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.reproduzir);
Button reproduzir = (Button) findViewById(R.id.reproduzir);
reproduzir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
play();
}
});
Button fechar= (Button) findViewById(R.id.fechar);
fechar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (player.isPlaying()) {
player.stop();
player.release();
}
finish();
}
});
}
public void play(){
try {
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onStart(){
super.onStart();
sensor.registerListener(this,sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.values[0]>10.2
||event.values[1]>10.2
||event.values[2]>10.2){
play();
}
}
}
My problem is that when I run it, I can only play it once. If I press the button a second time or shake it again, it does nothing. Can anyone help?
The easy fix is to simply add player.reset() in your play() method BEFORE calling player.setDataSource(...).
You can only call setDataSource(...) once without resetting the player. It is legal to call reset() in any state however (even if the player isn't yet initialized).
In other words, even if it's the first time you've called play() it is OK to use the following code in your play() method...
try {
player.reset();
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
}
// Your catch blocks here
Try to use:
mediaPlayer.reset()
after:
mediaPlayer.stop()
instead of release.
You can only set data source once.
in you code everytime the user presses the button you do this:
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
whice is wrong.
you need to setdata and prepare once and play how many times you want.
like so:
put this in you onCreate:
try {
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
in the onClick(View v), just have :
player.play();
Long story short - you have to use:
setLooping(true)
For more information about the Media Player check the post below. Take in mind the state diagram
http://developer.android.com/reference/android/media/MediaPlayer.html
MediaPlayer State diagram

How to add soundButton(on&off) on a activity in android apps?

I Have created a branch activity .Now i wanted to add two button on that branch activity.
When i click on 'sound on' button then my beep sound on start and when i clicked on 'sound off' then my beep sound off. and also they hide simultaneously.
Thank's
MY Code on Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sound_layout);
soundBttnOn =(Button) findViewById(R.id.soundBttnOn);
soundBttnOn.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v) {
startMediaPlayer();
}
}
);
soundBttnoff =(Button) findViewById(R.id.soundBttnOff);
soundBttnoff.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v) {
stopMediaPlayer();
}
}
);
}
private void startMediaPlayer() {
mediaPlayer = MediaPlayer.create(SoundLayout.this,R.raw.keybutton5);
mediaPlayer.start();
}
private void stopMediaPlayer() {
if( mediaPlayer != null ) {
MediaPlayer mp = null;
mp.stop();
mp.release();
}
}
It showing no problem but it is not working too..:P..I am not able to implement sound.
You can do simple google search to find tons of samples for adding button. However for playing sound file check out the MediaPlayer class.
Button startBtn, stopBtn;
//get the reference of Button
....
final MediaPlayer mp = new MediaPlayer();
startBtn.onClickListener() {
public void onClick(View v) {
try {
mp.setDataSource(path+"/"+audio.mp3);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
stopBtn.onClickListener() {
public void onClick(View v) {
if(mp.isPlaying()) {
mp.stop();
//hide buttons
stopBtn.setVisibiltiy(View.GONE);
startBtn.setVisibility(View.GONE);
}
}
};
PS: For only on and off, you don't need two buttons, you could do with one button.
EDIT:
For single button, just use the playing state of Media player for deciding about the action to take on button click.
singleBtn.onClickListener() {
public void onClick(View v) {
try {
if(mp.isPlaying()) mp.stop();
else {
mp.setDataSource(path+"/"+audio.mp3);
mp.prepare();
mp.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};

Streaming MediaPlayer will not work with Samsung Galaxy S3

Streaming MediaPlayer not working on Samsung galaxy s3. Don't have device myself but getting reports of it not working. Also tried Remote Test Lab and does not work. I have tested on many other devices and all work excepted for s3. Any help would be awesome!
Code:
public class Radio extends Activity {
private MediaPlayer mp;
private ImageButton pauseicon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
Toast.makeText(this, "Just one moment please", Toast.LENGTH_LONG).show();
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
getActionBar().setDisplayHomeAsUpEnabled(true);
/**
* Play button click event plays a song and changes button to pause
* image pauses a song and changes button to play image
* */
String res = "http://************";
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
mp.start();
}
});
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if (mp.isPlaying()) {
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if (mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (mp != null) {
if (mp.isPlaying())
mp.stop();
mp.release();
}
// there is no reason to call super.finish(); here
// call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
This is what I do to get a streaming music to play, just tested this on a Samsung Galaxy SIII and it is working fine. The audio stream in this is a public university radio stream. But this should work with other online streams. Just make sure you enable the internet permissions in your manifest.
public class MainActivity extends Activity {
MediaPlayer mpMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
mpMediaPlayer = new MediaPlayer();
mpMediaPlayer.setDataSource("http://streams.tsc.usu.edu:8888");
mpMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpMediaPlayer.prepare();
mpMediaPlayer.start();
}catch(Exception e){
e.printStackTrace();
}
}
This might be a little late, but for those who are coming to this looking for this answer, one solution might be to implement the MediaPlayer.OnPreparedListener.
public class MyActivity extends Activity implements MediaPlayer.OnPreparedListener
MediaPlayer mpMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
try{
mpMediaPlayer = new MediaPlayer();
mpMediaPlayer.setDataSource("audio url");
mpMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpMediaPlayer.prepare();
mpMediaPlayer.setOnPreparedListener(this);
}catch(Exception e){
e.printStackTrace();
Log.e(TAG, "Error loading media");
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mpMediaPlayer.start();
}

Categories

Resources