There is a play button(sound review), when I hit it plays, but when I hit several times, it plays multiply.
I wanted to stop this with other topic's codes, didn't help, any idea?
img_scream1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaControl.isPlaying()==true){
mediaControl.pause();
}
else
{
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
mediaControl.start();
}
}
});
Change your code to something like this:
boolean isPaused = true;
img_scream1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isPaused){
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
mediaControl.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
}
});
mediaControl.start();
isPaused = false;
}
else
{
mediaControl.pause();
isPaused = true;
}
}
});
Don't create the mediaControl instance every time(Which makes the song to load from begining). Instead, you can initialise mediaControl to null and create an instance of it when it is null
mediaControl =null;
img_scream1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
if (mediaControl == null) {
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
}
if (mediaControl.isPlaying() == true) {
mediaControl.pause();
} else {
mediaControl.start();
}
}
});
Related
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();
}
i create a true/false quiz app. in that app i have 4 buttons i.e True,False,previous(to get back to previous question),next(to get the next question). i want to add a functionality when a user click on true or false button its get disable for that question so the user can click only once for one question.
i tried to disable the button by using button.setEnabled(false) but when i click on previous button or next button the true/false buttons enabled.i want that the user can click the answer only once it does not matter how much the user traverse the question.
i try to call the setEnabledButton() in previous on click button but it disable the button but it also disable whether the user click on answer or not.
Button btrue,bfalse,bnext,bprevious;
TextView tquestion;
int mCurrentIndex=0;
Questions[] questionbank;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btrue=findViewById(R.id.true_button);
bfalse=findViewById(R.id.false_button);
bnext=findViewById(R.id.next_button);
tquestion=findViewById(R.id.question_text);
bprevious=findViewById(R.id.previous_button);
questionbank = new Questions[]
{
new Questions(R.string.greater,false),
new Questions(R.string.Pm,true),
new Questions(R.string.capital,true),
new Questions(R.string.china,false),
new Questions(R.string.Richer,false),
new Questions(R.string.company,true),
new Questions(R.string.company1,false),
};
update();
bnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int s=questionbank.length;
if( mCurrentIndex<=s )
{
if (mCurrentIndex + 1 < questionbank.length) {
mCurrentIndex++;
}
else
{ Toast.makeText(getApplicationContext(),"not more question",Toast.LENGTH_SHORT).show();
}
update();
}
}
});
btrue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(true);
}
});
bfalse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
bprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentIndex > 0) {
mCurrentIndex = (mCurrentIndex - 1);
update();
}
else
{ Toast.makeText(getApplicationContext(), "cant go back", Toast.LENGTH_SHORT).show(); }
}
});
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
setButtonEnabled(true);
}
private void checkAnswer(boolean userPressedTrue)
{
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
private void setButtonEnabled(boolean enabled) {
btrue.setEnabled(enabled);
bfalse.setEnabled(enabled);
}
}
In Questions class you can create a method,
public class Questions {
boolean isQuestionAnswered;
public boolean isQuestionAnswered() {
return isQuestionAnswered;
}
public void setQuestionAnswered(boolean questionAnswered) {
isQuestionAnswered = questionAnswered;
}
}
private void checkAnswer(boolean userPressedTrue)
{
questionbank[mCurrentIndex].setQuestionAnswered(true);
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
if(questionbank[mCurrentIndex].isQuestionAnswered())
setButtonEnabled(false);
else
setButtonEnabled(true);
}
Try this out and check whether this solves your problem
I am using this code but its not working i am still able to click more than 2 times.
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
accept.setEnabled(false);
if (dialog1 != null && dialog1.isShowing()) {
dialog1.dismiss();
}
handler.removeCallbacks(runnable);
}
});
its not showing any error but not working as desired.
boolean run = true;
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(run) {
run = false;
//your code
}
}
});
I want to change the song with a variable but can not do that.
Button btnSpeaker = (Button)findViewById(R.id.btnSpeaker);
btnSpeaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer file = MediaPlayer.create(MainActivity.this , R.raw.file1);
file.start();
}
});
final MediaPlayer mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.file1);
Button btnSpeaker = (Button)findViewById(R.id.btnSpeaker);
final int[] resources={R.raw.file1,R.raw.file2};
btnSpeaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int resource;
//if u meant getting resource variable from the file name
resource=getApplicationContext().getResources().getIdentifier("file2","raw",getPackageName());
//or
resource=resources[index];
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(getApplicationContext().getResources().openRawResourceFd(resource).getFileDescriptor());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
Button btnSpeaker = (Button)findViewById(R.id.btnSpeaker);
btnSpeaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp;
mp=MediaPlayer.create(getApplicationContext(), getResources().getIdentifier(word.toLowerCase(),"raw",getPackageName()));
mp.start();
}
});
I am playing audio files(MP3) by clicking on Item view, and the previous file stop automatically but the problem is that after tapping 3rd item of recyclerview the 1st one does not play sound on its click and the same problem happened on some other clicks of the list. I have added full Adapter class
public class RingToneAdapter extends RecyclerView.Adapter<RingToneAdapter.RingToneViewHolder> {
//removed declared varaible for the sake of post to edit
static final int[] resID = {R.raw.a48, R.raw.funny_hen};
public RingToneAdapter(Context rcntx, List<RingTone_Items> ringtonelist) {
this.rcntx = rcntx;
this.ringtonelist = ringtonelist;
}
#NonNull
#Override
public RingToneViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
view = LayoutInflater.from(rcntx).inflate(R.layout.ringtone_values, viewGroup, false);
RingToneViewHolder ringToneViewHolder = new RingToneViewHolder(view);
return ringToneViewHolder;
}
//playing sounds on recycler view
#Override
public void onBindViewHolder(#NonNull final RingToneViewHolder ringToneViewHolder, final int i) {
final RingTone_Items ringTone_items = ringtonelist.get(i);
ringToneViewHolder.rtv.setText(ringTone_items.getRintonetv());
if (mSelectedItem == i) {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
mSelectedItem = -1;
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged();
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
if (oldpossssssss == i) {
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
}
});
}
#Override
public int getItemCount() {
return ringtonelist.size();
}
class RingToneViewHolder extends RecyclerView.ViewHolder {
private TextView rtv, hello, close;
private ImageView iconplay;
public RingToneViewHolder(#NonNull View itemView) {
super(itemView);
rtv = itemView.findViewById(R.id.ringtitle);
iconplay = itemView.findViewById(R.id.playicon);
}
}
How can I manage this smoothly according to click the play media file accordingly. Where is I am doing wrong please help me Thanks.
I would suggest you to use singletone media player in your viewHolders. Firstly, using multiple prepared mediaPlayers are not very memory efficient. Secondly, it will allow you to resolve problems with played sound on the background because one mediaPlayer will play only one audio at a time.
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged();
if (oldpossssssss == i) {
if(mp != null){
if(mp.mp.isPlaying()){
mp.pause();
} else{
mp.start();
}
}
} else {
createMediaPlayer(i)
}
}
});
Use this method when you create MediaPlayer
private void createMediaPlayer(int i)
{
if (mp!=null)
{
if(mp.isPlaying())
{
mp.stop();
mp.reset();
mp.release();
mp=null;
}
}
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
May be its work.