Countdown with individual Sound - java

I have a problem with my countdown and I want to play an individual sound at the end. For this I have created a list. When the corresponding picture is clicked, the selection should be saved and played in this method:
private void loadMusic() {
if (timerStatus == TimerStatus.PAUSED)
new Runnable() {
#Override
public void run() {
playSound(R.raw.sound1);
}
public void playSound(int sound1) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), (R.raw.sound2));
mp.start();
}
}.run()
}
I tried to solve this with an array in the onCreate method, but this is "void" and therefore I don't get a return:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.sound);
final int[] selection = new int[1];
imageButton1 = findViewById(id.iv_bowl1);
imageButton1.setOnClickListener(v -> {
selection[0] = 1;
Toast.makeText(Sound.this, "1-click", Toast.LENGTH_SHORT).show();
});
return selection[0];
}
Thanks for help.

Related

Start loop and stop code with single button click

I want to make a simple button which will start to loop a function every period of time which I can set. But not only it will start the loop, but also stop the loop if I click the button again. Is there anyway I can achieve this with a single button?
Here's how I'd do it
public class MainActivity extends AppCompatActivity {
private Button btn;
private View.OnClickListener runOnClickListener;
private View.OnClickListener stopOnClickListener;
void init() {
Handler handler = new Handler();
int duration = 5000;
Runnable runnable = new Runnable() {
#Override
public void run() {
foo();
handler.postDelayed(this, duration);
}
};
runOnClickListener = view -> {
runnable.run();
btn.setOnClickListener(stopOnClickListener);
};
stopOnClickListener = view -> {
handler.removeCallbacks(runnable);
btn.setOnClickListener(runOnClickListener);
};
btn.setOnClickListener(runOnClickListener);
}
void foo() {
Log.i("foo", "foo");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
init();
}
}
Yeah, give you a simple example.
First, create two constant values and one instance variable:
//indicate whether or not the loop is running
private boolean isRunning = false;
//used for handler to send empty msg
private final static int MSG_LOOP = 1;
private final static long LOOP_INTERVAL = 5000;
Then create a Handler instance to handle the loop logic:
Handler handler = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_LOOP:
doStuff();
break;
}
}
};
private void doStuff() {
//after what you want to do is done, send another MSG_LOOP msg with delay
handler.sendEmptyMessageDelayed(MSG_LOOP, LOOP_INTERVAL);
}
And finally:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRunning) {
//cancel if any in the message queue
handler.removeMessages(MSG_LOOP);
} else {
//if you do not want to start the loop immediately, then use: "sendEmptyMessageDelayed"
handler.sendEmptyMessage(MSG_LOOP);
}
}
});

Runnable not running

I am writing a program that calculates pi with a given amount of iterations. I want to be able to time how long this takes and how much power is being used. I have another version of this application that works perfectly but, with the same code, this version won't.
Most of the code is working fine but the powerRunnable code is not executing when it is called.
any thoughts?
public class MainActivity extends AppCompatActivity {
//GUI
TextView piResultTextView, timeResultTextView,
powerResultTextView, voltageTextView, averageCurrentTextView;
EditText piEditText;
Button calculateButton, stopButton;
TextView countView;
//GLOBAL VARIABLES
Results results;
Handler powerHandler = new Handler();
Runnable powerRunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "here", Toast.LENGTH_SHORT).show();
long millis = System.currentTimeMillis() - results.initialTime;
timeResultTextView.setText(getString(R.string.display_time, millis));
double current = getCurrent();
results.totalCurrent += current;
results.count++;
double power = current * results.voltage;
results.powerConsumption += power;
countView.setText(String.valueOf(results.count));
powerHandler.postDelayed(this, 1);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
piEditText = findViewById(R.id.PiEditText);
calculateButton = findViewById(R.id.CalculateButton);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!empty()) {
results = new Results(getVoltage());
results.initialTime = System.currentTimeMillis();
powerHandler.postDelayed(powerRunnable, 0);
calculatePi(piEditText.getText().toString());
finalizeResults();
displayResults();
}
}
});
stopButton = findViewById(R.id.StopButton);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
piResultTextView.setText("");
timeResultTextView.setText("");
powerResultTextView.setText("");
voltageTextView.setText("");
averageCurrentTextView.setText("");
powerHandler.removeCallbacks(powerRunnable);
}
});
piResultTextView = findViewById(R.id.PiResultTextView);
timeResultTextView = findViewById(R.id.TimeResultTextView);
powerResultTextView = findViewById(R.id.PowerResultTextView);
voltageTextView = findViewById(R.id.VoltageTextView);
averageCurrentTextView = findViewById(R.id.AverageCurrentTextView);
countView = findViewById(R.id.CountView);
}
#Override
public void onPause() {
super.onPause();
powerHandler.removeCallbacks(powerRunnable);
}
public void finalizeResults() {
results.endTime = System.currentTimeMillis();
powerHandler.removeCallbacks(powerRunnable);
results.powerConsumption *= 1000;
}
public void displayResults() {
piResultTextView.setText(results.pi);
timeResultTextView.setText(getString(R.string.display_time, results.getTime()));
powerResultTextView.setText(getString(R.string.display_power, results.powerConsumption));
voltageTextView.setText(getString(R.string.display_voltage, results.getVoltage()));
averageCurrentTextView.setText(getString(R.string.display_current, results.getAverageCurrent()));
}
}
I try to use your part of code in my application:
Handler powerHandler = new Handler();
Runnable powerRunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "here", Toast.LENGTH_SHORT).show();
powerHandler.postDelayed(this, 1);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
powerHandler.postDelayed(powerRunnable, 0);
}
And its working.

mediaplayer how to stop all sounds?

When I press the mute button on action bar that I have created it only stops the last sound being played and not all the sounds.
Also since the sound doesn't stop if I press the button(5-6 times) to play the sound and press mute on the same activity then go back and choose another activity and press that mute button the app crashes. Any ideas why?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
public void pb1(View view) {
mp = MediaPlayer.create(this, R.raw.sound1);
mp.start();
}
//inflates the menu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menunot, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sound:
mp.stop();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.stop();
mp.reset();
mp.release();
mp = null;
}
Just make an array list then stop all,
Take a look at the example below:
private static final int steps[] =
{R.raw.step_1, R.raw.step_2, R.raw.step_3, R.raw.step_4, R.raw.step_5, R.raw.step_6, R.raw.step_7, R.raw.step_8, R.raw.step_9, R.raw.step_10
};
private int i = 0;
private ArrayList<MediaPlayer> voices = new ArrayList<>(10);
private Button btnPlay;
private Button btnStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(i==10)i=0;
final MediaPlayer voice = MediaPlayer.create(MainActivity.this, steps[i++]);
voice.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (voice != null) {
voices.remove(voice);
voice.release();
}
}
});
voice.start();
voices.add(voice);
}
});
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int j = voices.size() - 1; j >= 0; j--) {
if (voices.get(j) != null) {
if (voices.get(j).isPlaying())
voices.get(j).stop();
voices.get(j).release();
voices.remove(j);
}
}
}
});
}
Hey please try the following solution,
SoundPool is a much better alternative for this purpose. I would caution strongly against instantiating multiple MediaPlayer instances as most systems do not have the resources to generate many parallel active instances. You will find on many device that hitting the button upwards of 5 times will cause a memory based crash.
As far as stopping all active streams, there is not baked-in function for this, but it's easy to accomplish in a manner to similar to your existing code. As a side note, there is an autoPause() method, which halts all streams, but it doesn't truly end their playback (as the method name insinuates). Here is a simple example to manage your audio streams:
//SoundPool initialization somewhere
SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
//Load your sound effect into the pool
int soundId = pool.load(...); //There are several versions of this, pick which fits your sound
List<Integer> streams = new ArrayList<Integer>();
Button item1 = (Button)findViewById(R.id.item1);
item1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int streamId = pool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
streams.add(streamId);
}
});
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Integer stream : streams) {
pool.stop(stream);
}
streams.clear();
}
});
It is much more memory efficient to manage a list of streamID values than MediaPlayer instances, and your users will thank you. Also, note that it is safe to call SoundPool.stop() even if the streamID is no longer valid, so you don't need to check for existing playback.
Happy coding :)

setOnCompletionListener issue

Hey guys I'm totally new to java, trying to finish my first project for college. I want to finish the code with setting OnCompletionListener to set the sound to null. So, it looks like this:
package com.example.alaiborys.newfuckingshit;
public class campfire extends AppCompatActivity {
MediaPlayer campfiresound;
int paused;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_campfire);
}
public void play(View view) {
if (campfiresound == null) {
campfiresound = MediaPlayer.create(this, R.raw.campfire);
campfiresound.start();
}
else if(!campfiresound.isPlaying())
{
campfiresound.seekTo(paused);
campfiresound.start();
}
}
public void stop(View view) {
campfiresound.release();
campfiresound = null;
}
public void pause(View view) {
campfiresound.pause();
paused = campfiresound.getCurrentPosition();
}
}
So, I want to add OnCompletionListener(): but have no idea where to put it and how to code it, any idea?
Well that is pretty easy...you have a media player object campfiresound
so you need to regisdter the interface OnCompletionListener
campfiresound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//toast...am done!!
}
});

Updating android ui with timer

i am new to android programming, i searched through all the answers about this topic but still i am not able to implement what i want to do. My problem is: i want to update the picture at imageview with another picture in given periods. The imageview is needed to be updated with different pictures every time, total of 15-20 times. Here is what i have done so far but it is not working at all.
public class IlkMasal extends Activity {
MediaPlayer sound;
private Handler m_handler;
private ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firsttale);
m_handler = new Handler();
Button menu = (Button)findViewById(R.id.Button01);
Button startbutton = (Button)findViewById(R.id.button1);
sound = MediaPlayer.create(this, R.raw.music4);
sound.start();
image = (ImageView)findViewById(R.id.imageView1);
image.setImageResource(R.drawable.picture2);
startbutton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
m_handler.removeCallbacks(m_statusChecker);
m_handler.postDelayed(m_statusChecker, 2000);
}
});
menu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent main= new Intent("android.intent.action.MAIN");
startActivity(main);
}
});
}
Runnable m_statusChecker = new Runnable()
{
public void run(){
image.setImageResource(R.drawable.picture3);
m_handler.removeCallbacks(m_statusChecker);
m_handler.postDelayed(m_statusChecker, 2000);
}
};
}
After i click startbutton i want to update the ui with different pictures every time. I will appreciate your help.
Yo can set this runnable to run on your onClic and you will still need a method to get the next picture you want to show.
final int delay = 5000;
final int period = 1000;
final Runnable r = new Runnable() {
public void run() {
image.setImageResource(getNextPicture());
postDelayed(this, period);
}
};
postDelayed(r, delay);
Regards.
use runOnUiThread for Updating UI Elements from NON Ui Thread as:
Current_Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
image.setImageResource(R.drawable.picture3); //Update UI elements here
}
});

Categories