I want to play a sound on button click in game.
I can easily do this using following code
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
Issue is, my clicking rate is faster then playing duration of my sound clip.
How do I stop it and play again on my second or third click and so on.
I want to match sound play to match my clicking rate.
Thanks
Abhinav Tyagi
Firstly, you should use MediaPlayer only for large files, like music. For playing sound effects, SoundPool is the way to go.
An excellent tutorial on playing back media is available HERE.
On the click of your button, call soundPool.stop() and soundPool.play() immediately in sequence to stop and start your audio playback.
You can call MediaPlayer.Stop to stop it playing sounds. You can also call MediaPlayer.Reset to return it to the Idle state.
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer;
public void startPlay(View view) {
mplayer.start();
}
public void stopPlay(View view) {
mplayer.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mplayer = MediaPlayer.create(this, R.raw.laugh);
}
}
Related
If i am playing song from a song list and if the other song is already playing then both songs plays simultaneously in android studio. If i just use next or previous buttons then they are working fine. The problem is through song list. I am not getting how to check if media player is playing already or not in this condion. I am doing this code in kotlin and i am new user of android studio.
you can check this way
You can take a global variable of MediaPlayer
public MediaPlayer mediaPlayer;
and then create in onCreate method:
mediaPlayer= MediaPlayer.create(this, R.raw.xxxx);
and thus your play method will be:
public void mediaPlay(View view) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
else{
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
}
i create an app, and in one layout (just call it layout A), i play the media player, then when i went to another layout (just call it Layout B), i want the sound from the Layout A is continue playing in Layout B, and when i went back to the Layout A, i also want the media player is still continuing the music that was played before.
In Layout A, i set this code in onCreate:
player = MediaPlayer.create(this, R.raw.sound);
if(!isMuted())
{
player.setLooping(true);
player.start();
}
...
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent intent = new Intent(A.this, B.class);
stop=1;
startActivity(intent);
}
});
And this code:
#Override
protected void onPause()
{
super.onPause();
if (stop!=1)
{
//stop=1 if i go to another layout, for example when i want to go to Layout B
//if the device is automatically locked, i want the media player is paused and it resumed when i unlock the device, so i use stop!=1 to know whether the sound should be paused or not
player.pause();
length = player.getCurrentPosition();
}
}
#Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
//isMuted is method to know whether the sound is muted or not, if it isn't muted, then the sound is resumed
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
In layout B, i used this code in onCreate:
player = MediaPlayer.create(this, R.raw.sound);
....
And this code:
protected void onPause()
{
super.onPause();
player.pause();
length = player.getCurrentPosition();
}
#Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
if(player.isPlaying())
{
}
else
{
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
}
But this is the problem.
When i went to Layout B, the Media Player from Layout A and Media Player from Layout B is played in the same time, so the sound is played simultaneously at one time.
When i went back to the Layout A, the Media Player in Layout B is stopped and the Media Player in Layout A is stopped and played from the beginning again, it didn't continue the Media Player that was played before.
When the device is locked, the media player is still played although i have used the indicator whether is should be paused or not. Any correction to the code?
I would recommend that you use a Service to play and pause/stop your music. It is not recommended to use Activity to handle music that way. You can start a Service and then play music in it. Services run in background and don't get destroyed automatically too often as compared to Activity. Here's a sample app code that does similar to what you need media player sound continue in all activities
In Activity MediaPlayer can play far.
You should use Service to play MediaPlayer and control from anywhere in application.
I used this tutorial.
https://thenewcircle.com/s/post/60/servicesdemo_using_android_service
I am trying to play two sound items, one after the other
MediaPlayer mp = null;
protected void produceErrorSound(int index) {
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, index);
mp.start();
}
public void correctAnswerAndNext(){
produceErrorSound(R.raw.right1) ;
produceErrorSound(R.raw.right1) ;
}
but only second sound is produced.
is there any alternative approach?
I can't see any wait mechanism in your code.
You can use an onCompletionListener to receive a callback when your first MediaPlayer has finished playback. At that point you can start the second MediaPlayer.
An alternative way in Jellybean (and later versions) is to use the audio chaining functionality (i.e. setNextMediaPlayer) to automatically start another MediaPlayer as soon as the current one has finished playing. Something like this (I've omitted the calls to setDataSource etc for brevity):
mediaPlayer1.prepare();
mediaPlayer2.prepare();
mediaPlayer1.start();
mediaPlayer1.setNextMediaPlayer(mediaPlayer2);
I have an android app with a button that plays a sound. the code for playing the sound:
if (mp != null)
{
mp.release();
}
mp = MediaPlayer.create(this, R.raw.match);
mp.start();
mp is a field in the activity:
public class Game extends Activity implements OnClickListener {
/** Called when the activity is first created. */
//variables:
MediaPlayer mp;
//...
The app runs ok, but after clicking the button about 200 times on the emulator, app crashed and gave me this error https://dl.dropbox.com/u/5488790/error.txt (couldn't figure how to post it here so it will appear decently)
i am assuming this is because the MediaPlayer object is consuming up too much memory, but isn't mp.release() supposed to take care of this? What am i doing wrong here?
If you are attaching a sound effect to a button, MediaPlayer in general is far too heavyweight for this operation. You're getting unnecessary latency each time just to load up the sound data into memory. You should look at using SoundPool instead.
In either case, there is no valid reason to release and re-create the MediaPlayer each time. If you decide to use MediaPlayer, control the single instance you have with the button clicks.
MediaPlayer mp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Other init code
//Create the player this way so it doesn't auto-prepare
mp = new MediaPlayer();
AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.match);
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
}
public void onDestroy() {
super.onDestroy();
//Release it only when no longer needed
mp.release();
mp = null;
}
public void onButtonClick(View v) {
if (mp.isPlaying()) {
mp.stop();
}
//Play the sound
mp.prepare();
mp.start();
}
Hope that Helps, but again, I would highly recommend using SoundPool instead if this sound is just a short effect.
It looks like your code should work, but obviously release() isn't really releasing everything.
Maybe it's because you have to reload R.raw.match every time you want to play the sound. If R.raw.match is just a short sound effect, then you might want to consider using SoundPool instead.
If you use SoundPool you only have to load R.raw.match once which may prevent the memory issues.
This tutorial has a good example on how to use it: http://www.vogella.com/articles/AndroidMedia/article.html#tutorial_soundpool
You pretty much just make one instance of SoundPool then load the sound once and play it when you need it.
Hope this helps!
Edit
If you want to use MediaPlayer...
public class Blah extends Activity implements OnClickListener {
MediaPlayer mp;
#Override
public void onCreate(Bundle b)
{
// blah blah
mp = MediaPlayer.create(R.raw.match);
// blah blah
}
#Override
public void onClick(View v)
{
if (v.getId() == yourButtonID)
{
// play sound from beginning
mp.seekTo(0);
mp.start();
}
}
}
This way you only create one instance and whenever you want to play it, you just rewind it to the beginning then play.
Try
if (mp != null)
{
mp.release();
}
mp = MediaPlayer.create(this, R.raw.match);
mp.prepare(); // not needed
mp.start();
Good luck!!
if you hold the MediaPlayer, release it at the end of the activity
#Override
void onDestroy() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
super.onDestroy();
}
I'm playing around with Android to learn the API and I'm trying to code an activity which can listen for changes in audio events. For example, the activity I created plays a random ringtone when you press a button. The button displays a text saying "Random Ringtone", but when you press the button it says "Stop" and pressing it will, of course, stop playing the ringtone.
However, the problem is that when the ringtone stops playing on its own, the button still says "stop".
I've looked around to try to find an event listener that could listen for when the ringtone stops playing, but I can't seem to find one. I've seen some info out there about creating your own listeners, but I'm not interested in doing that (a little advanced for me right now).
Does an event listener of this type exist?
I may be wrong but I think the only audio class which raises an event when it finishes playing is the MediaPlayer class. Something like this should work...
public class MyActivity extends Activity
implements MediaPlayer.OnCompletionListener {
MediaPlayer player = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
player = new MediaPlayer();
player.setOnCompletionListener(this);
...
}
#Override
public void onCompletion(MediaPlayer mp) {
// Called when playback is complete
...
}
}