Replace an image in android/Java once a sound has stopped playing - java

I have an app which replaces an image and plays a sound on click of a button, What I am looking to do is revert back to the original image once the sound has stopped playing.
My button click listener:
public void onClick(View v) {
// Perform action on click
Context context = getApplicationContext();
CharSequence text = "Playing Theme";
int duration = Toast.LENGTH_SHORT;
//this is the replaced image while the sound is playing
imgSheep.setImageResource(R.drawable.replacedimage);
Toast.makeText(context, text, duration).show();
playSound(R.drawable.sound);
}
My Sound playing function:
//plays a sound file
private void playSound(int sFile) {
//set up MediaPlayer
final int medFile = sFile;
Thread thread = new Thread(new Runnable() {
public void run() {
playSound = MediaPlayer.create(getApplicationContext(), medFile);
playSound.start();
}
});
thread.start();
}
I know I can use a method like:
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
performOnEnd();
}
});
So can I have it like this:
playSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer playSound) {
imgSheep.setImageResource(R.drawable.originalimage);
}
});

Your problem is your thread. In playSound, you're starting a new thread which creates the media player and plays the sound. However you're setting the onCompletionListener in onCreate. There's a race condition there- if the new thread isn't schedules and doesn't run and set the mediaPlayer variable before you hit that line, you'll crash with a NullPointerError.
I suggest just losing the thread. MediaPlayer already will play in the background and not hang the UI thread.

Related

Adding music in android studio (java, MediaPlayer)

buttonMusic = findViewById(R.id.buttonMus);
musicSound = MediaPlayer.create(this, R.raw.music);
buttonClick();
}
private Button buttonMusic;
private MediaPlayer musicSound;
public void buttonClick() {
buttonMusic.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay(musicSound);
}
}
);
}
public void soundPlay(MediaPlayer sound) {
if (sound.isPlaying()) {
sound.stop();
}else {
sound.start();
sound.setLooping(true);
} }
Hello.
The code launches the music, is able to stop it, but it wont play again after pressing the play button, after pausing the song that is.
you aren't pausing song, you are stop()ing it. use sound.pause() for pausing :)
after stop() MediaPlayer you have to prepare it again, use prepare() or prepareAsync(). MediaPlayer.create( makes that for you at the beginning, also if you would create MediaPlayer using its constructor you would also want to prepare()/preapreAsync() before calling start() in onClick
check out state diagram of MediaPlayer

onResume to restart playing background music is not working

this is my first app so this question/answer might be pretty basic.
I currently have onPause(); , to stop the music playing when player leaves the screen. I've tried to do a similar thing but with onResume, so that the music plays again (backgroundMusic). Unfortunately this isn't working. It does work again when I press the reset button or go back to the home page and come back to the game page. But it just doesn't load as soon as the app is back on screen, like I would like it to.
My code excerpt follows;
package com.example.android.buttongame;
...
public class MainActivity extends AppCompatActivity {
...
MediaPlayer winningSound;
MediaPlayer buttonSound;
MediaPlayer backgroundMusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
Plays ticking background noise at the start of this activity. Set on a loop
*/
backgroundMusic = MediaPlayer.create(this, R.raw.ticking_background);
backgroundMusic.start();
backgroundMusic.setOnErrorListener(new android.media.MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mediaplayer, int i, int j)
{
return false;
}
});
backgroundMusic.setLooping(true);
}
#Override
public void onResume(){
super.onResume();
backgroundMusic.start();
}
public void onPause() {
super.onPause();
backgroundMusic.stop();
}
...
public void reset(View v) {
/*
Plays button sound
*/
buttonSound = MediaPlayer.create(MainActivity.this, R.raw.button_sound);
buttonSound.start();
/*
* Refreshes activity
*/
this.recreate();
}
...
public void homePage (View view) {
/*
Stops background music
*/
backgroundMusic.stop();
/*
Plays button sound
*/
buttonSound = MediaPlayer.create(MainActivity.this, R.raw.button_sound);
buttonSound.start();
/*
Leads to home page
*/
Intent homePage = new Intent(this, HomePage.class);
startActivity(homePage);
}
}
At the place of backgroundMusic.stop(), you should use backgroundMusic.pause() then you will achieve what you are looking for.
Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.
Calling stop() has no effect on a MediaPlayer object that is already in the Stopped state.
Here is the documentation of MediaPlayer that will help you to understand about its APIs.
https://developer.android.com/reference/android/media/MediaPlayer

Playing audio repeat Android studio

I am playing some audio via a button is pressed. The audio plays fine, but i want to be able to spam the button and let the audio play play play play. Even stop where its playing and play again if i press the button. Now when i press the button, the audio just plays all the way through and nothing happens if i press the button while the audio is playing. Here is my code:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.audio1);
Button play_button = (Button)this.findViewById(R.id.button1);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
final MediaPlayer mp = MediaPlayer.create(this, R.raw.audio1);
mp.setLooping(true);
Button play_button = (Button)this.findViewById(R.id.button1);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
Replace this code with your existing code. if you want to repeat your audio then you have to set the looping property to true.
OK - I hope I got this right:
You want to play the audio clip for every time you press the button and the clip should be played completely, before the next clip starts.
Here's what I'd do:
Create a new integer attribute.private int i = 0;
Increment it every time you press the button.
Button play_button = (Button)this.findViewById(R.id.button1);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
IUP();
}
});
public synchronized void IUP(){
i++;
}
public synchronized void IDOWN(){
i--;
}
public synchronized int getI(){ return i; }
public void startAudio(){ mp.start(); }
public boolean isPlaying(){ return mp.isPlaying(); }
Use a seperate thread for the player.
Thread player_thread = new Thread(new Runnable(){
#Override
public void run(){
while(true){
if(getI() > 0 && !isPlaying()){
IDOWN();
startAudio();
}
}
}
}).start();
Or use an OnCompletionListener on the MediaPlayer.
Tell me if this is what you were looking for.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.audio1);
Button play_button = (Button)this.findViewById(R.id.button1);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(play_button.getText().toString().equals("Stop")
{
mp.stop();
play_button.setText("Play");
}
else
{
mp.start();
play_button.setText("Stop");
}
}
});

Beginner android help playing audio from within a runnable

I'm playing around with some basic android, and I'm trying to write a metronome app. The basic idea is that I'm using a runnable in order to trigger a sound after a time period (msPeriod). I've tried to use SoundPool, but it will just log 'sample not loaded', and trying to ititialise a MediaPlayer causes the app to crash on opening. Could you explain to me where I'm going wrong please? Below is my code with MediaPlayer.
//I create the media player first thing inside MainActivity
private Handler handler = new Handler();
int msPeriod = 1000;
MediaPlayer mpHigh = MediaPlayer.create(this, R.raw.hightick);
MediaPlayer mpLow = MediaPlayer.create(this, R.raw.lowtick);
//within an onClick Listener
onClick(View v) { handler.postDelayed(startMetron, msPeriod); }
//the runnable that starts the metronome
private Runnable startMetron = new Runnable( ) {
#Override
public void run() {
if(isRunning){
if (count == 4) {
count = 1;
mphigh.start();
} else {
count++;
mplow.start();
}
}
textCount.setText(String.valueOf(count));
//triggering the next run
handler.postDelayed(this, msPeriod);
}
};
Thanks so much for bearing with me!
You are running a separate thread . The UI element must be updated form the main thread... so..
runOnUiThread(new Runnable(){
public void run() {
textCount.setText(String.valueOf(count));
}
});
This makes sure that the textview is update from the UI thread and your app will not crash.

Android: button is not changing to pause state when i click

i have coded for media player and it is playing song .In the front end only image button is used and hardcoded as play button
when i click again it has to change image to pause state but the button which i have used is playing the song two times simultaneously whenever i click on it which is wrong
but i need the song to be paused so whereever i used
mp.start();
function which will be start to play the music from the url i added the code as
if(!mp.isPlaying()){
mp.start();
buttonPlayPause.setBackgroundResource(R.drawable.pause);
}else {
mp.pause();
buttonPlayPause.setBackgroundResource(R.drawable.play);}
but when i click the play button it starts playing and again if i click the button again it starts playing two times simultaneously
please help me how should i start and pause the mp3 file which i have displayed it in url it is not going to else block itself should i use different function
the full code of the project is
public class MainActivity5 extends Activity implements OnClickListener,
OnPreparedListener, OnErrorListener, OnCompletionListener {
MediaPlayer mp;
ProgressDialog pd;
Button bt;
ImageButton iv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main5);
iv = (ImageButton)findViewById(R.id.play);
iv.setOnClickListener(this);}
#Override
public void onPrepared(MediaPlayer mp)
{
Log.i("StreamAudioDemo", "prepare finished");
//pd.setMessage("Playing.....");
//mp.start();
/*if(mp.isPlaying()== true)
{
mp.start();
iv.setImageResource(R.drawable.pause);
}
else
{
mp.pause();
mp.release();
iv.setImageResource(R.drawable.play);
}*/
}
#Override
public void onClick(View v) {
try
{
pd = new ProgressDialog(this);
pd.setMessage("Buffering.....");
//pd.show();
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setDataSource("http://192.168.1.138/Android/music/vande.mp3");
mp.prepareAsync();
mp.setOnCompletionListener(this);
}
catch(Exception e)
{
Log.e("StreamAudioDemo", e.getMessage());
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
pd.dismiss();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
pd.dismiss();
Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
}}
thanks for your help in advance
i have commented some code above i have to re correct it
you can have a try at your onclickListener,when this player is playing,if you want to pause it ,you should to call MediaPlayer.pause() ,if you want to release it data,you can call MediaPlayer.release(),then ,you can play next music.
use this
public void onPrepared(MediaPlayer mp)
{
Log.i("StreamAudioDemo", "prepare finished");
//pd.setMessage("Playing.....");
// mp.start(); - this should be removed
if(mp.isPlaying()== true)
{
mp.pause();
iv.setImageResource(R.drawable.pause);
}
else
{
mp.start();
mp.release();
iv.setImageResource(R.drawable.play);
}
}

Categories

Resources