i am trying to play media file with the following code using floating action button.
it works fine so far but it keeps playing even when i switch to another activity. I want to stop media player when back button pressed. Please help me...
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final MediaPlayer mp = new MediaPlayer();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("audio/sound.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onBackPressed() {
//here i want to stop media player with back button
super.onBackPressed();
}
Override OnDestroy and add below code:
#Override
public void onDestroy() {
if (mp != null) mp.release();
}
Related
I have made one sample application in which is just having two buttons
1. Start (to Start music)
2. Stop (to stop music).
Here is my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button b1 = (Button) findViewById(R.id.button_start);
b1.setOnClickListener(this);
Button b2 = (Button) findViewById(R.id.button_stop);
b2.setOnClickListener(this);
mp = MediaPlayer
.create(getApplicationContext(), R.raw.alarm);
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setLooping(true);
mp.setVolume(0.5f,0.5f);
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.button_start:
startAlarm();
break;
case R.id.button_stop:
stopAlarm();
}
}
private void stopAlarm() {
if(mp.isPlaying()) {
Log.e("XXX","Tone Paused");
mp.pause();
}
new Thread(new Runnable() {
#Override
public void run() {
while(mp.isPlaying()){
Log.e("XXX", "tone still playing ...");
}
Log.e("XXX", "Thread stopped");
}
}).start();
}
private void startAlarm() {
mp.start();
}
}
Now I saw that mp.pause() is being called and mp.isPlaying() is returning false after that. But the music is continuously playing it never stops until I power off the device.
I am not sure whether this is a bug of android os or hardware. I checked with other android 6.0 devices but it was working fine.
Can someone please suggest me the possible root cause of this?
Thanks in advance!!!
Change your stopAlarm() method
private void stopAlarm() {
if(mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
}
}
I have a loop-all button and a stop button. Both buttons work fine while I'm still on the page. The problem is when I hit the loop-all button, it plays a series of audio files as it is supposed to, but when I leave the page (i.e. hit the phone's back button) and come back to the page, the audio doesn't stop! I hit the stop button, but it does nothing. The only way to stop it is to go into task manager and end the program. It seems to me that the reference of mp2 gets lost once I leave the page...Does anyone have any suggestions on how to fix this. Any help would be appreciated. Here is the code:
public class OneVoc extends ActionBarActivity {
private ListView lv;
private MediaPlayer mp;
private MediaPlayer mp2;
int[] myAudio = {R.raw.v_1100, R.raw.v_1101, R.raw.v_1102, R.raw.v_1103, R.raw.v_1104, R.raw.v_1105,
R.raw.v_1113, R.raw.v_1106, R.raw.v_1107, R.raw.v_1108, R.raw.v_1109, R.raw.v_1110, R.raw.v_1112,
R.raw.v_1114, R.raw.v_1115, R.raw.v_1116};
int mCompleted = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_voc);
Button btnLoop = (Button) findViewById(R.id.button1);
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp2 != null) {
if (mp2.isPlaying()) {
mp2.setOnCompletionListener(null);
mp2.stop();
}
mp2.reset();
mp2.release();
mp2 = null;
}
}
});
btnLoop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp2 = MediaPlayer.create(getBaseContext(), myAudio[0]);
mp2.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp2)
{
mCompleted++;
mp2.reset();
if (mCompleted < myAudio.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(myAudio[mCompleted]);
if (afd != null)
{
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp2.prepare();
mp2.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted == myAudio.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(myAudio[mCompleted]);
if (afd != null)
{
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp2.prepare();
mp2.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp2.release();
mp2 = null;
}
}
});
mp2.start();
}
});
try overriding onbackpressed method
#Override
public void onBackPressed()
{
// code here to stop and finish()
super.onBackPressed();
}
I think it's an It's an Audio buffer issue, memory is loaded in audio buffer and persist later on,finish() might not help u.
When u press back button on an android button it simply calls the finish() for current activity, while when u press home button it calls onPause(),
You need to override onBackPressed() method, and before line super.onbackPressed();
Put your code to stop playing.
When u go to TakMgr it simply get's the PID refer to ur App process and kills the process.
Which is like System.exit(0); or android.os.process.kill(getMyPid());
Which simply ends ur app which u do not want.
Can you pause your mp in onPause() and restart it in onResume()?
Maybe you want also to store in savedInstance at which point you were!
Hope it's helpful
when you back press the activity just stop the mediaplayer and free the resources and finish the activity.that's it..!
#Override
public void onBackPressed()
{
btnStop.performClick();
super.onBackPressed();
}
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 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();
}
Recently I started with Android.
I'm trying to do a small example to understand how the sound output with android.
To this I build me a program that plays an mp3 file, and while this playing can change the sound output to:
Internal Speaker
External Speaker
Headset
Earpiece
Is this possible?
I have part of the code done, but do not know how to jump from a sound output to another.
public class TestAudioActivity extends Activity {
private MediaPlayer mediaPlayer;
private ImageButton playButton;
private ImageButton pauseButton;
private ImageButton stopButton;
AudioManager audioManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeMediaPlayer();
playButton = (ImageButton) findViewById(R.id.playButton);
pauseButton = (ImageButton) findViewById(R.id.pauseButton);
stopButton = (ImageButton) findViewById(R.id.stopButton);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null)
mediaPlayer.start();
else
initializeMediaPlayer();
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
/** if (mediaPlayer != null)
mediaPlayer.pause(); */
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(false);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
});
}
private void initializeMediaPlayer() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("http://server3.pianosociety.com/protected/bach-bwv772-stahlbrand.mp3");
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// Mostramos mensaje en caso de error.
Toast.makeText(getApplicationContext(), "URL no encontrada", 2000);
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone help?
Thank you.
I have never played with media activities yet, but yes you can change your sound output while playing for example you can use
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);