How to start & stop a sound with a button? - android

I have a Button in my project.
I want when Button clicked>>>> start a sound
and when Button clicked again>>> stop the sound...
I use this code but can't stop the sound and start it again and again...
How can I do this?
Thank you.
Button btritm1 = (Button) findViewById(R.id.button9991);
btritm1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final MediaPlayer mp1_1 = MediaPlayer.create(MainActivity.this, R.raw.ritm1);
if (event.getAction() == MotionEvent.ACTION_DOWN )
{
if(mp1_1 != null && mp1_1.isPlaying() )
{
mp1_1.stop();
}
else {
// xritm1 = 1;
// snd.stop_s_ritm1();
mp1_1.setLooping(true);
mp1_1.start();
}
} // end of if
return false;
}
}); // end of ontouch listener/*

if(sound.isPlaying()){
sound.stop();
}else{
sound.reset();
sound.setDataSource(yourURL);//or InputStream etc.
sound.prepare();
sound.start();
}

To use a good practice, declare the MediaPlayer object as a class variable and initialize it in your onCreate() method. Your problem is that a new player object is created each time your control is touched.
So as was already said above, the line
final MediaPlayer mp1_1 = MediaPlayer.create(MainActivity.this, R.raw.ritm1);
should be outside the Listener.

Related

Hello. I'm making a lyrics app which can also play the music of the lyrics

what I'm trying to do is add 1 button that will play and stop the music. is it possible to loop them like 1st click play then 2nd click stop 3rd click will start from beginning and 4th stops again and so on?
based on my search on google it's something like this? sorry if noob question
public void playtd(View view) {
if(!td.isPlaying()) {
td.start();
}
else if(td.isPlaying()) {
td.pause();
}
}
Try This:
MediaPlayer td;
boolean isPrepared;
public void prepareMediaPlayer(Uri yourTrackUri){
// call this on initialization of your mediaplayer
sMRMediaPlayer = MediaPlayer.create(mContext, uri);
sPrepared = true;
}
public void playtd(View view) {
if (!isPrepared) {
prepareMediaPlayer(Uri yourTrackUri)
}
if(!td.isPlaying()) {
td.start();
else {
// reprepare mediaplayer
td = MediaPlayer.create(Context, uriToUrFile);
isPrepared = true;
}
} else { // stop playing instead of pause, stop will start playing next time u play from beginning
td.stop();
}
void releaseMediaPlayer() {
if (td!= null) {
Log.d(TAG, "MediaPlayer is released.");
td.reset();
td.release();
td= null;
isPrepared = false;
}
}
call releaseMediaPlayer once done with all play and stop stuff (may be on destroy etc.)
initialize mediaplayer by passing track uri to prepareMediaPlayer
add try catch, wherever needed

Keep a sound sample playing till button is released android

I am trying to implement a musical keyboard application that will play string sounds. String sounds are needed to be played till the user releases the key.
I am using a small sample of 1 second with the idea of looping the sample using SoundPool on
MotionEvent.ACTION_DOWN,
and stopping it as
ACTION_UP
gets called. But looping does not seem to work. I can put a "long enough" sound sample assuming no user would keep the button pressed for that long, but that is not quite the way I want the app work.
What should I do?
Try this code:
inside onCreate()
mp=MediaPlayer.create(MainActivity.this,R.raw.beep);
b.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mp.setLooping(true);
mp.start();
}
if (event.getAction() == MotionEvent.ACTION_UP) {
mp.stop();
mp=MediaPlayer.create(MainActivity.this,R.raw.beep);
}
return false;
}
});

Playing default android sound of button, clicking onTouch() method

In my android app I have some buttons, that should work with onTouch() method, course I need to change button's text, when finger in ACTION_DOWN position. But this buttons should to play default android sound of button clicking (like in onClick() method). Where I can find such sound? I think, it must be in SDK, but how can I find it? And what methods are better for such operation? I'm using MediaPlayer.
Listing:
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
addTextShadow(v);
Log.v(LOG_TAG, "ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
clearTextShadow(v);
isMoved = true;
Log.v(LOG_TAG, "ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.v(LOG_TAG, "ACTION_UP");
if (!isMoved) {
clearTextShadow(v);
if (v.getId() == R.id.btn_new) {
Log.v(LOG_TAG, "New pressed");
playSound(); //MY METHOD TO PLAY SOUND
} else if (v.getId() == R.id.btn_saved) {
Log.v(LOG_TAG, "Saved pressed");
} else if (v.getId() == R.id.btn_random) {
Log.v(LOG_TAG, "Random pressed");
}
}
isMoved = false;
break;
}
return true;
}
And my playSound() method:
public void playSound(){
if (mp != null) {
mp.release();
mp = null;
}
try {
mp = MediaPlayer
.create(MyActivity.this, R.raw.sound); //BUT HERE I NEED DEFAULT SOUND!
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Use this code in your onTouch() method:
view.playSoundEffect(android.view.SoundEffectConstants.CLICK);
If you are simply looking for a preset Android sound then it's better to use this functionality that's provided to you for free by the framework. Doing anything else, unless necessary for customization, would simply result in you working against the framework instead of working with it.
Use default sounds from /system/media/audio/
MediaPlayer or SoundPool will help to implement playback.
Consider using view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);.
It will do both: playing the default sound and vibrate if the user has it enabled in the global settings.

How to start and stop a sound in android?

I have a button called " micro" , when I click on my sound is played , and when I click on again it must stop
I tried the code below but when I click on my button for the second time , the music is played again and again without stopping:
Button micro=(Button)findViewById(R.id.micro);
micro.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.mymusic);
mp.start();
}
if(event.getAction() == MotionEvent.ACTION_UP){
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.mymusic);
mp.stop();
}
return true;
}
});
You are creating separate MediaPlayer objects. You should just create one that you tell to start and stop as necessary.
Right now you're telling one to start, and then later telling a different one to stop.

How to detect when VideoView starts playing (Android)?

Here's the problem, I want to change play button to pause button when the video stream starts playing in videoview but I don't know how to detect that event?
There is a great article about MediaPlayer in here - http://www.malmstein.com/blog/2014/08/09/how-to-use-a-textureview-to-display-a-video-with-custom-media-player-controls/
You can set infoListener on your VideoView
setOnInfoListener(new MediaPlayer.OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
// Here the video starts
return true;
}
return false;
}
I ended up using VideoView.setOnPreparedListener. This was enough to cover my problem (play button drawable change to pause)
accepted answer here is not 100% accurate.
sometimes onprepared is call 3 seconds before first frame is being rendered. i suggest having a callback on that event (MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
mMediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
if (i == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START){
//first frame was bufered - do your stuff here
}
return false;
}
});
see media info documantaion for more callbacks of info/warning:
https://developer.android.com/reference/android/media/MediaPlayer.html#MEDIA_INFO_VIDEO_RENDERING_START
As far as I know, there is no event sent when video start playing in VideoView, but I can think of two options:
Create a version of VideoView by yourself, that sends event in those cases.
Use MediaController (which is default in VideoView)
If you want to follow option one - you can get the source of VideoView from here
isPlaying() can be called to test whether the MediaPlayer object is in the Started
Android MediaPlayer.isPlaying()
Another way to detect if videoview started is using videoView.getCurrentPosition(). getCurrentPosition() returns 0 if streaming not started.
protected Runnable playingCheck = new Runnable() {
public void run() {
while (true) {
if (vw.getCurrentPosition() != 0) {
// do what you want when playing started
break;
} else {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Then call:
new Thread(playingCheck).start();
Please try this :
final Handler h = new Handler();
h.postDelayed( new Runnable() {
public void run() {
if (videoView.getCurrentPosition() != 0) {
((ProgressBar) rootView.findViewById(R.id.pgStreaming)).setVisibility(View.GONE);
} else {
h.postDelayed(this, 250);
}
}
}, 250);

Categories

Resources