How can I implement the "pause" function in my MediaPalyer? - java

The "stop" and "play" work fine, but "pause" works like "stop". When I press pause, the audiofile stops playing and when I press play, it starts from the beginning.
The "stop" and "play" work fine, but "pause" works like "stop". When I press pause, the audiofile stops playing and when I press play, it starts from the beginning.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class HelloMoonFragment extends Fragment
{
private AudioPlayer mPlayer = new AudioPlayer();
private Button mPlayButton;
private Button mStopButton;
private Button mPauseButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_hello_moon, parent, false);
mPlayButton = (Button)v.findViewById(R.id.hellomoon_playButton);
mPlayButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
mPlayer.play(getActivity());
}
});
mPauseButton = (Button) v.findViewById(R.id.hellomoon_pauseButton);
mPauseButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
mPlayer.pause();
}
});
mStopButton = (Button)v.findViewById(R.id.hellomoon_stopButton);
mStopButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
mPlayer.stop();
}
});
return v;
}
#Override
public void onDestroy()
{
super.onDestroy();
mPlayer.stop();
}
}
package com.example.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer {
private MediaPlayer mPlayer;
public void stop()
{
if(mPlayer != null)
{
mPlayer.release();
mPlayer = null;
}
}
public void pause()
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
}
}
public void play(Context c)
{
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
stop();
}
});
mPlayer.start();
}
}

it starts from the beginning because here:
public void play(Context c) {
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
you are releasing the old one a create it again
Try remembering the the player is paused:
public class AudioPlayer {
boolean isPaused = false;
public void pause() {
if(mPlayer.isPlaying()) {
mPlayer.pause();
isPaused = true;
}
}
public void play(Context c) {
if (isPaused && mPlayer != null) {
mPlayer.start();
isPaused = false
return;
}
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);

Related

Can I have multiple onStop methods in Android code?

image shows a screenshot of the app interfaceI am very new to writing any kind of code, and am attempting to build an app that can host two podcasts. I want users to be able to play two separate podcasts on the app, and so need to use two separate onStop methods. However, I get the error:
onStop()' is already defined in "app name"
Is there a way to implement 2 separate onStop methods?
package com.example.breastiesapp;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
public class MindActivity extends AppCompatActivity {
public Button button;
MediaPlayer mediaPlayer;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mind);
mediaPlayer = null;
//Body Button
button = (Button) findViewById(R.id.bodyBTN);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MindActivity.this,BodyActivity.class);
startActivity(intent);
}
});
//Home Button
button = (Button) findViewById(R.id.homeBTN);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MindActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
//Play Pod 1
public void PlayPod1(View view) {
switch (view.getId()) {
case R.id.btnPlayPod1:
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.pod1feelmorejoy);
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopPod1();
}
});
mediaPlayer.start();
break;
case R.id.btnPausePod1:
if (mediaPlayer !=null)
mediaPlayer.pause();
break;
case R.id.btnStopPod1:
if (mediaPlayer != null) {
mediaPlayer.stop();
stopPod1();
}
break;
}
}
private void stopPod1() {
mediaPlayer.release();
mediaPlayer = null;
}
#Override
protected void onStop() {
super.onStop();
stopPod1();
}
//Play Pod 2
public void PlayPod2(View view) {
switch (view.getId()) {
case R.id.btnPlayPod2:
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.usingmindfulnesstoreducestressandstrengthenyourimmune);
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopPod2();
}
});
mediaPlayer.start();
break;
case R.id.btnPausePod2:
if (mediaPlayer !=null)
mediaPlayer.pause();
break;
case R.id.btnStopPod2:
if (mediaPlayer != null) {
mediaPlayer.stop();
stopPod2();
}
break;
}
}
private void stopPod2() {
mediaPlayer.release();
mediaPlayer = null;
}
#Override
protected void onStop() {
super.onStop();
stopPod1();
}
}

Music doesn't play again after I press home or recents button

I have an app with a button to play or pause music. Pressing the back button while playing music pauses it and opening the app again resumes the music after pressing the play button. But that doesn't work with home or recents button. The music pauses but upon reopening the app and pressing the play button doesn't play the music until a force close. Here is the code:
package com.example.firozkaoo2222.myapplication;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import static com.example.firozkaoo2222.myapplication.R.raw.police;
public class MainActivity extends AppCompatActivity {
private MediaPlayer policeSound = MediaPlayer.create(this, police);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button policeSounds = this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (policeSound == null) {
policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
}
if (policeSound.isPlaying()) {
policeSound.pause();
} else {
policeSound.start();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (policeSound != null) {
policeSound = MediaPlayer.create(this, R.raw.police);
policeSound.start();
}
}
#Override
public void onPause() {
super.onPause();
if (policeSound.isPlaying())
policeSound.pause();
}
//Back button pressed.
#Override
public void onBackPressed() {
super.onBackPressed();
if (policeSound.isPlaying())
policeSound.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
policeSound.stop();
policeSound = null;
}
}
If you press home button the app go to the background and when you came from the background you should override the method onResume();
Code:
public class MainActivity extends AppCompatActivity {
//THIS IS YOUR LAST MISTAKE. IF YOU TRY TO CREATE THE OBJECT WITH THE CONTEXT AND THE RESOUERCES
//WHEN THE ACTIVITY IS NOT CREATED YET, YOUR APP CRASH
//private MediaPlayer policeSound = MediaPlayer.create(this, R.raw.police);
private MediaPlayer policeSound;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button policeSounds = this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (policeSound == null) {
policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
}
if (policeSound.isPlaying()) {
policeSound.pause();
} else {
policeSound.start();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (policeSound != null) {
policeSound = MediaPlayer.create(this, R.raw.police);
policeSound.start();
}
}
#Override
public void onPause() {
super.onPause();
if (policeSound.isPlaying())
policeSound.pause();
}
//Back button pressed.
#Override
public void onBackPressed() {
super.onBackPressed();
if (policeSound.isPlaying())
policeSound.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
policeSound.stop();
policeSound = null;
}
}
I hope this help you.

Runtime error in thread of music app

**Down here I am trying to build a music app in android studio,my app is working fine displaying all my SD card songs and play too ,all button works but when I click on next button it works normally but don't know why app sometimes gets stopped working and shows runtime exception ->>please open the image of run log of the application.
package com.example.ramandeepsingh.tunes;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.jar.Manifest;
public class PlayerActivity extends AppCompatActivity{
static MediaPlayer mp;//assigning memory loc once or else multiple songs will play at once
int position;
SeekBar sb;
ArrayList<File> mySongs;
Thread updateSeekBar;
Button pause,forward,reverse,next,previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
pause = (Button)findViewById(R.id.pause);
forward = (Button)findViewById(R.id.forward);
previous = (Button)findViewById(R.id.previous);
next = (Button)findViewById(R.id.next);
reverse = (Button)findViewById(R.id.reverse);
sb=(SeekBar)findViewById(R.id.seekBar);
updateSeekBar=new Thread(){
#Override
public void run(){
int totalDuration = mp.getDuration();
int currentPosition = 0;
// sb.setMax(totalDuration);
while(currentPosition < totalDuration){
try{
sleep(500);
currentPosition=mp.getCurrentPosition();
}
catch (InterruptedException e){
e.printStackTrace();
System.out.println(e);
}
sb.setProgress(currentPosition);
}
}
};
if(mp != null){
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songs");
position = b.getInt("pos",0);
Uri u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
if(mp.isPlaying()){
pause.setText(">");
mp.pause();
}
else {
pause.setText("||");
mp.start();
}
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
mp.seekTo(mp.getCurrentPosition()+5000);
}
});
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
mp.seekTo(mp.getCurrentPosition()-5000);
}
});
next.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.reset();
position=((position+1)%mySongs.size());
Uri u = Uri.parse(mySongs.get( position).toString());
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.release();
position=((position-1)<0)?(mySongs.size()-1):(position-1);
Uri u = Uri.parse(mySongs.get( position).toString());//%mysongs so that it do not go to invalid position
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
}
});
}}

Radio app don't run at background

I have radio app which streams online radio. But it don't work on background i.e when i press home button phone automatically shut it down. how do i make it run on background.
package com.radioawaz.simerpreetjassal.radioawaz;
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 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) {
Log.e("ready!","ready");
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("http://streaming.shoutcast.com/Radioawazca?lang=en-ca");
} 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();
}
}
}
All above is my main Activity. please look and give suggestion.Thanks in advance.

Implementing Music Across Activities

Problem: When I use the home button to close the app the music continues playing. So I manually close the app by killing the activity, the music stops... for a few seconds and then starts again (and this time a restart is in order to turn it off).
MusicService.class:
package com.MyApp.App;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MusicService extends Service implements
MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MusicService() {
}
public class ServiceBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.test_music);
mPlayer.setOnErrorListener(this);
if (mPlayer != null) {
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return START_STICKY;
}
public void pauseMusic() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
length = mPlayer.getCurrentPosition();
}
}
public void resumeMusic() {
if (mPlayer.isPlaying() == false) {
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic() {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
return false;
}
}
MainPage.class:
package com.MyApp.App;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
public class MainPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
Intent music = new Intent();
music.setClass(this, MusicService.class);
startService(music);
}
#Override
protected void onDestroy() {
super.onDestroy();
mServ.stopMusic();
}
#Override
protected void onPause() {
super.onPause();
mServ.pauseMusic();
}
#Override
protected void onStop() {
super.onStop();
mServ.stopMusic();
}
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder) binder).getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
void doBindService() {
bindService(new Intent(this, MusicService.class), Scon,
Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(Scon);
mIsBound = false;
}
}
}
(NOTE: I have taken excerpts from my app, so I may have forgotten imports in this code, but all imports are correctly included in the app.)
Fixed:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
doBindService();
Intent music = new Intent();
music.setClass(this, MusicService.class);
startService(music);
}
and
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
please red : onCreate, OnPause , OnResume

Categories