How can I make the music stop? - java

So I made a media Player that works fine but I have one big problem, after pressing play, if I close the activity or app, the music continues to play, if I click again, the music plays on the other one, and I don't know how to fix it. I just want the music to stop after closing the activity or app without any problem.
Here is the full code:
public class m1 extends AppCompatActivity {
ImageView backm1, replay, forward, btPlay, btPause;
TextView playerPosition, playerDuration;
CircularSeekBar seekBar;
MediaPlayer mediaPlayer;
Handler handler = new Handler();
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m1);
backm1 = (ImageView) findViewById(R.id.backm1);
backm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m1.super.onBackPressed();
}
});
playerPosition = findViewById(R.id.playerPosition);
playerDuration = findViewById(R.id.playerDuration);
replay = findViewById(R.id.replay);
forward = findViewById(R.id.forward);
seekBar = findViewById(R.id.seekBar);
btPause = findViewById(R.id.btPause);
btPlay = findViewById(R.id.btPlay);
mediaPlayer = MediaPlayer.create(this,R.raw.ding_dong);
runnable = new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(this,500);
}
};
int duration = mediaPlayer.getDuration();
String sDuration = convertFormat(duration);
playerDuration.setText(sDuration);
btPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btPlay.setVisibility(View.GONE);
btPause.setVisibility(View.VISIBLE);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
handler.postDelayed(runnable, 0);
}
});
btPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.pause();
handler.removeCallbacks(runnable);
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if(mediaPlayer.isPlaying() && duration != currentPosition){
currentPosition = currentPosition + 10000;
playerPosition.setText(convertFormat(currentPosition));
mediaPlayer.seekTo(currentPosition);
}
}
});
replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
if (mediaPlayer.isPlaying() && currentPosition > 10000){
currentPosition = currentPosition - 10000;
playerPosition.setText(convertFormat(currentPosition));
mediaPlayer.seekTo(currentPosition);
}
}
});
seekBar.setOnSeekBarChangeListener(new CircularSeekBar.OnCircularSeekBarChangeListener() {
#Override
public void onProgressChanged(CircularSeekBar circularSeekBar, float v, boolean b) {
if (b) {
mediaPlayer.seekTo((int) v);
}
playerPosition.setText(convertFormat(mediaPlayer.getCurrentPosition()));
}
#Override
public void onStopTrackingTouch(CircularSeekBar circularSeekBar) {
}
#Override
public void onStartTrackingTouch(CircularSeekBar circularSeekBar) {
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btPause.setVisibility((View.GONE));
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.seekTo(0);
}
});
}
#SuppressLint("DefaultLocale")
private String convertFormat(int duration) {
return String.format("%02d:%02d"
,TimeUnit.MILLISECONDS.toMinutes(duration)
,TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer !=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
I added onDestroy but I think in a wrong way and this error came out:
2021-03-08 10:13:40.843 419-4716/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags: } when converting to stream
2021-03-08 10:13:40.906 28868-28868/com.example.diligent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.diligent, PID: 28868
java.lang.IllegalStateException
at android.media.MediaPlayer.getCurrentPosition(Native Method)
I added this:
private void stopPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
Toast.makeText(this, "MediaPlayer released", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
And the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
Any other suggestions are welcome.
Thank you in advance.

Stop and release media resources on onDestroy of activity.
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer !=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}

MediaPlayer player; //MediaPlayer object
*Function to stop media Player *
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "MediaPlayer released", Toast.LENGTH_SHORT).show();
}
}
Call the function in onStop() callback
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}

Related

Pass username to another activity with RewardedAd

The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}

Playing multiple clips the same time android studio - use threads?

Im creating an app in android studio where I want 10 clips to be played at the same time side by side. Im having some problems with some lags already at three clips and I wounder if Im better off using threads? In that case how?
Any hint would be very much apreciated
Here is my code so far. I know it is not very efficient and I am better off using an array of a player object for example but Im just testing so far:
public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
private MediaPlayer mp1, mp2, mp3;
private TextureView tv1, tv2, tv3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = findViewById(R.id.textureView1);
tv2 = findViewById(R.id.textureView2);
tv3 = findViewById(R.id.textureView3);
tv1.setSurfaceTextureListener(this);
tv2.setSurfaceTextureListener(this);
tv3.setSurfaceTextureListener(this);
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
Surface surface = new Surface(surfaceTexture);
mp1 = MediaPlayer.create(this, R.raw.a7);
mp1.setSurface(surface);
// mp1.prepareAsync(); //
mp1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp1) {
mp1.start();
}
});
Surface surface2 = new Surface(surfaceTexture);
mp2 = MediaPlayer.create(this, R.raw.a9);
mp2.setSurface(surface2);
// mp1.prepareAsync(); //
mp2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp2) {
mp2.start();
}
});
Surface surface3 = new Surface(surfaceTexture);
mp3 = MediaPlayer.create(this, R.raw.a10);
mp3.setSurface(surface3);
// mp1.prepareAsync(); //
mp3.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp3) {
mp3.start();
}
});
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
#Override
protected void onPause() {
if (mp1 != null && mp1.isPlaying()) {
mp1.pause();
}
super.onPause();
}
#Override
protected void onResume() {
if (mp1 != null) {
mp1.start();
}
super.onResume();
}
#Override
protected void onDestroy() {
if (mp1 != null) {
mp1.stop();
mp1.release();
mp1 = null;
}
super.onDestroy();
}
}
You should play media in a different non-ui thread. like this:-
public class MediaService extends Service {
private MediaPlayer mp1, mp2, mp3;
private static final String ACTION_START = TAG + ".ACTION_START";
private IBinder mBinder = new MyBinder();
private MediaPlayer.OnPreparedListener mMediaPrepared = new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "MediaPlayer.onPrepared");
onCommandPlay(mp);
}
};
#Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "onBind");
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
m1 = MediaPlayer.create(this, R.raw.a1);
m2 = MediaPlayer.create(this, R.raw.a2);
m3 = MediaPlayer.create(this, R.raw.a9);
}
#Override
public void onDestroy() {
super.onDestroy();
if (m1 != null) m1 .release();
if (m2 != null) m2 .release();
if (m3 != null) m3 .release();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String action = intent.getAction();
Log.d(TAG, "onStartCommand: " + intent.getAction());
if (ACTION_START.equals(action)) {
onCommandStart();
return START_STICKY;
}
stopSelf();
return Service.START_STICKY_COMPATIBILITY;
}
/**
* Performs actions related to media player when Service onStartCommand method is called
*
*/
private void onCommandStart() {
// Create Notifications with remote views
mNotification = new NotificationCompat.Builder(this).setTicker("Media Service started...")
.setSmallIcon(R.mipmap.ic_launcher)
.setContent(collapsed)
.setAutoCancel(false)
.setOngoing(true)
.build();
startForeground(NOTIFICATION_ID, mNotification);
startPlaying();
}
private void onCommandPlay(MediaPlayer mp) {
try {
mp.start();
} catch (IllegalStateException e) {
Log.e(TAG, "onCommandPlay", e);
}
}
/**
* Start playing the provided media item
*
*/
private void startPlaying() {
mCurrent = item;
try {
mp1.reset();
mp1.setOnPreparedListener(mMediaPrepared);
mp2.reset();
mp2.setOnPreparedListener(mMediaPrepared);
mp3.reset();
mp3.setOnPreparedListener(mMediaPrepared);
AssetFileDescriptor afd1 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a9););
AssetFileDescriptor afd2 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a10););
AssetFileDescriptor afd3 = getResources().openRawResourceFd(getResources().openRawResourceFd(R.raw.a8););
mp1.setDataSource(afd1 .getFileDescriptor(), afd1 .getStartOffset(), afd1.getLength());
mp2.setDataSource(afd2 .getFileDescriptor(), afd2 .getStartOffset(), afd2 .getLength());
mp3.setDataSource(afd3 .getFileDescriptor(), afd3 .getStartOffset(), afd3 .getLength());
mp1.prepareAsync();
mp2.prepareAsync();
mp3.prepareAsync();
} catch (IOException e) {
Log.e(TAG, "startPlaying", e);
}
}
public class MyBinder extends Binder {
public MediaService getService() {
return MediaService.this;
}
}
}
then start the service from Activity like this:
Intent intent = new Intent(context, MediaService.class);
intent.setAction(ACTION_START);
startServie(intent);
You should also handle different media playing use-cases. You can refer this link for more.

i want to stop current playing audio when user click on next play button

I am facing problem in my app. All the audios are playing well but the problem is when I press on the first button to start playing audio, it plays it and if I click on next play button that also starts playing but the first audio does not stop. how to stop that. please help
Here, my app java code :
public class ringtone_tab extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtone_tab);
clk6 = (Button) findViewById(R.id.btn_play6);
clk5 = (Button) findViewById(R.id.btn_play5);
clk4 = (Button) findViewById(R.id.btn_play4);
clk3 = (Button) findViewById(R.id.btn_play3);
clk2 = (Button) findViewById(R.id.btn_play2);
clk1 = (Button) findViewById(R.id.btn_play1);
mdx6 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_vandana);
mdx5 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_tandav_mantra);
mdx4 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shiv_om);
mdx3 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shiv);
mdx2 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_aaradhna);
mdx = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shankar);
}
public void setBtn_play6(View v)
{
if(mdx6.isPlaying())
{
mdx6.stop();
mdx6.reset();
mdx6.release();
}
mdx6 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_vandana);
mdx6.start();
}
public void setBtn_play5(View v)
{
if(mdx5.isPlaying())
{
mdx5.stop();
mdx5.reset();
mdx5.release();
}
mdx5 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_tandav_mantra);
mdx5.start();
}
public void setBtn_play4(View v)
{
if(mdx4.isPlaying())
{
mdx4.stop();
mdx4.reset();
mdx4.release();
}
mdx4 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv_om);
mdx4.start();
}
public void setBtn_play3(View v)
{
if(mdx3.isPlaying())
{
mdx3.stop();
mdx3.reset();
mdx3.release();
}
mdx3 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv);
mdx3.start();
}
public void setBtn_play2(View v)
{
if(mdx2.isPlaying())
{
mdx2.stop();
mdx2.reset();
mdx2.release();
}
mdx2 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_aaradhna);
mdx2.start();
}
public void setBtn_play1(View v)
{
if(mdx.isPlaying())
{
mdx.stop();
mdx.reset();
mdx.release();
}
mdx = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shankar);
mdx.start();
}
}
Introduce new method call like stopAllplayers
private void stopAllPlayers(){
if(mdx1 != null && mdx1.isPlaying())
{mdx1.stop();mdx1.reset(); mdx1.release();}
if(mdx2 != null && mdx2.isPlaying())
{mdx2.stop();mdx2.reset(); mdx2.release();}
if(mdx3 != null && mdx3.isPlaying())
{mdx3.stop();mdx3.reset(); mdx3.release();}
if(mdx4 != null && mdx4.isPlaying())
{mdx4.stop();mdx4.reset(); mdx4.release();}
if(mdx5 != null && mdx5.isPlaying())
{mdx5.stop();mdx5.reset(); mdx5.release();}
if(mdx6 != null && mdx6.isPlaying())
{mdx6.stop();mdx6.reset(); mdx6.release();}
}
then call this method in all of your play methods.
public void setBtn_play6(View v)
{
stopAllPlayers()
........
do this for all setBtn_play1, setBtn_play2.....
Use below code with one media player
public class ringtone_tab extends AppCompatActivity {
Button clk1;
Button clk2;
Button clk3;
Button clk4;
Button clk5;
Button clk6;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtone_tab);
clk6 = (Button) findViewById(R.id.btn_play6);
clk5 = (Button) findViewById(R.id.btn_play5);
clk4 = (Button) findViewById(R.id.btn_play4);
clk3 = (Button) findViewById(R.id.btn_play3);
clk2 = (Button) findViewById(R.id.btn_play2);
clk1 = (Button) findViewById(R.id.btn_play1);
mediaPlayer = new MediaPlayer();
}
public void setBtn_play6(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_vandana);
mediaPlayer.start();
}
public void setBtn_play5(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_tandav_mantra);
mediaPlayer.start();
}
public void setBtn_play4(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv_om);
mediaPlayer.start();
}
public void setBtn_play3(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv);
mediaPlayer.start();
}
public void setBtn_play2(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_aaradhna);
mediaPlayer.start();
}
public void setBtn_play1(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shankar);
mediaPlayer.start();
}
private void stopPlayer(){
if(mediaPlayer != null && mediaPlayer.isPlaying())
{mediaPlayer.stop();}
}
}

Android MediaPlayer seekBar not working correctly

Currently, I'm developing a media player and I need seekBar to work together, at the moment, it's everything okay! but, when I touch at determinated position of the seekbar, the mediaplayer must follow and set the song to this determinated position, but the song and seekBar back to the start and I don't know why it's happening.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
public TextView song_detail;
public TextView time1;
public TextView time2;
private String player_status = "playing";
private ImageButton player_img;
public static SeekBar seekBar;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
song_detail = findViewById(R.id.song_detail);
song_detail.setVisibility(View.GONE);
time1 = findViewById(R.id.time_1);
time2 = findViewById(R.id.time_2);
seekBar = findViewById(R.id.seekBar);
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
if(mediaPlayer != null){
int CurrentPosition = mediaPlayer.getCurrentPosition();
String m_1;
String s_1;
seekBar.setProgress(CurrentPosition/1000);
final int minutes_1 = (CurrentPosition/1000)/60;
final int seconds_1 = ((CurrentPosition/1000)%60);
if (minutes_1 < 10) {
m_1 = "0" + minutes_1;
} else {
m_1 = "" + minutes_1;
}
if (seconds_1 < 10) {
s_1 = "0" + seconds_1;
} else {
s_1 = "" + seconds_1;
}
time1.setText(m_1 + ":" + s_1);
int Duration = mediaPlayer.getDuration();
String m_2;
String s_2;
final int minutes_2 = (Duration/1000)/60;
final int seconds_2 = ((Duration/1000)%60);
if (minutes_2 < 10) {
m_2 = "0" + minutes_2;
} else {
m_2 = "" + minutes_2;
}
if (seconds_2 < 10) {
s_2 = "0" + seconds_2;
} else {
s_2 = "" + seconds_2;
}
time2.setText(m_2 + ":" + s_2);
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
});
seekBar.setMax(mediaPlayer.getDuration()/1000);
mediaPlayer.start();
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public static void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
}
This is the part of code that I'm using to work with mediaPlayer and seekBar
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
But as I have said, instead of mediaPlayer seek and continue the audio from the position that I've clicked, the audio simply back to the start. What I'm doing wrong?
Thank you.
The max value for progress is 100. The seekTo function takes time in milliseconds. This is why it seeks to the start (almost) of the audio.
So instead of mediaPlayer.seekTo(progress);, you need to do:
long newTime = (progress/100.0) * total_audio_duration_in_millisecond;
mediaPlayer.seekTo(newTime);

How do I release my media player after it is done playing?

I am creating a sound board and after clicking about 30 different sounds it stops working; I believe android is running out of memory. Below is my code. How can I implement .release() so that when the sound is done playing it is released? I don't really care if two things play at the same time; the clips are t0o short for this to be possible. I would just like to get my code set.
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final MediaPlayer pg1 = MediaPlayer.create(this, R.raw.peter1);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.start();
}
});
I have done a lot of searching around but due to my lack of java/android knowledge I have not been able to get anything to work. Thanks in advance, let me know if anyone needs anymore code.
I left a comment, but I'll post an answer to show what I mean anyway...
The idea is that you have a set number of MediaPlayer instances that you can use. That way you never exceed the maximum number of instances. The array should be the length of the number of concurrent sounds you expect to be able to hear. If the sounds are local files, the length of time it takes to prepare the sounds should be almost negligible, so calling create inside the click handler should not result in terrible performance. Each of your buttons is associated with a particular resource, I suppose, so I set up a helper method to create and play the sounds for each button in the same way.
public class soundPageOne extends Activity {
private MediaPlayer[] mPlayers = new MediaPlayer[2];
private int mNextPlayer = 0;
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
Button playSound1 = (Button)this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSound(R.raw.peter1);
}
});
}
public void onDestroy() {
super.onDestroy(); // <---------------------- This needed to be there
for (int i = 0; i < mPlayers.length; ++i)
if (mPlayers[i] != null)
try {
mPlayers[i].release();
mPlayers[i] = null;
}
catch (Exception ex) {
// handle...
}
}
private void startSound(int id) {
try {
if (mPlayers[mNextPlayer] != null) {
mPlayers[mNextPlayer].release();
mPlayers[mNextPlayer] = null;
}
mPlayers[mNextPlayer] = MediaPlayer.create(this, id);
mPlayers[mNextPlayer].start();
}
catch (Exception ex) {
// handle
}
finally {
++mNextPlayer;
mNextPlayer %= mPlayers.length;
}
}
}
Create a class, say AudioPlayer with a SoundPool variable. Setup a constructor to initialise the AudioPlayer object and create a Play method. SoundPool works better for short sounds played many times and does not require you to release.
public class AudioPlayer {
private SoundPool sPool = new SoundPool(Integer.MAX_VALUE, AudioManager.STREAM_MUSIC, 0);
public AudioPlayer(Context c, int id){
sounds.put("1",sPool.load(c, id, 1));
}
public void play(Context c) {
sPool.play("1", 1, 1, 1, 0, 1f);
}
}
So your class should look like
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final AudioPlayer ap = new AudioPlayer(this, R.raw.sound);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ap.play();
}
});
Could you use a MediaPlayer.OnCompletionListener?
Something like:
public class soundPageOne extends Activity implements MediaPlayer.OnCompletionListener {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final MediaPlayer pg1 = MediaPlayer.create(this, R.raw.peter1);
//***set the listener here***
pg1.setOnCompletionListener(this);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.start();
}
});
}
//***this code will be executed once the sound finishes playing***
#Override
public void onCompletion(MediaPlayer mp) {
//log messages, other things can go here
mp.release();
}
Try something like this
Your activity class:
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final AudioPlayer pg1 = new AudioPlayer();
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.play(this, R.raw.sound);
}
});
}
This is another Java Class:
public class AudioPlayer {
private MediaPlayer mPlayer;
public void stop() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
public void play(Context c, int sound) {
stop();
mPlayer = MediaPlayer.create(c, sound);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
stop();
}
});
mPlayer.start();
}
public boolean isPlaying() {
return mPlayer != null;
}
}

Categories

Resources