Save state of MediaPlayer on rotation - android

I am working on an app that has included an radio and everything is fine the play, stop, and pause buttons. My problem is that whenever a song is playing and I press the back button and reopen the app the buttons won't work with the current streaming radio
This happens as well when I change the orientation. Is there a way I can save the state of the media player and then obtain the state so that I can stop the song that is being played?
public class radioActivity extends AppCompatActivity {
Button b1;
private Button Button1;
private Button Button2;
private String STREAM_URL = "http://192.99.35.93:6370/;stream.mp3";
private MediaPlayer mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
Button button1 = (Button) findViewById(R.id.buttonpredica1);
Button button2 = (Button) findViewById(R.id.buttonpredica2);
mPlayer = new MediaPlayer();
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
WifiManager.WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wifiLock.acquire();
wifiLock.release();
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mPlayer.reset();
mPlayer.setDataSource(STREAM_URL);
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mPlayer) {
mPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});

This happens because every time you either press back or rotate your device, your activity is destroyed and with it goes all of its state. If you want your app to keep playing under such circumstances (which makes total sense for a radio app), you'll need to implement the media playback logic in a service:
https://developer.android.com/guide/components/services.html
Regarding your need to deal with media playback in background, there is a very complete official documentation page on this topic:
https://developer.android.com/guide/topics/media/mediaplayer.html

Create a new object or class that is not GUI related that handles the radio.
in the constructor of your GUI add a parameter MediaPlayer that then sets the respective field to the Media Player.
Adjust the code of the buttons to interact with the Media Player Field.
This will allow for you to open/close various windows that interact with the same MediaPlayer.
public radioactivity(MediaPlayer mPlayer) {
this.mPlayer = mPlayer;
}

Related

How to make letter sound on cliсking by them? [duplicate]

How do I get a button to play a sound from raw when click? I just created a button with id button1, but whatever code I write, all is wrong.
import android.media.MediaPlayer;
public class BasicScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
}
Button one = (Button)this.findViewById(R.id.button1);
MediaPlayer = mp;
mp = MediaPlayer.create(this, R.raw.soho);
zero.setOnCliclListener(new View.OnClickListener() )
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.basic_screen, menu);
return true;
}
}
This is the most important part in the code provided in the original post.
Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
To explain it step by step:
Button one = (Button) this.findViewById(R.id.button1);
First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById, passing the Id we assigned to it (in this example's case: R.id.button1), to get the button that we need. We cast it as a Button so that it is easy to assign it to the variable one that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
This is how to initialize a MediaPlayer. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create() method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho. We declare it as final. Jon Skeet provided a great explanation on why we do so here.
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//code
}
});
Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener of our button one. Inside is only one method, onClick() which contains what instructions the button should do on click.
public void onClick(View v) {
mp.start();
}
To play the sound, we call MediaPlayer's start() method. This method starts the playback of the sound.
There, you can now play a sound on button click in Android!
Bonus part:
As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release() method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener to our mp like so:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//code
}
});
Inside the onCompletion method, we release it like so:
public void onCompletion(MediaPlayer mp) {
mp.release();
}
There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment or Activity that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.
Original Post
First. You should put your statements inside a block, and in this case the onCreate method.
Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.
Third, put the logic to play the sound inside the onClick.
In summary:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BasicScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
}
}
Tested and working 100%
public class MainActivity extends ActionBarActivity {
Context context = this;
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mp = MediaPlayer.create(context, R.raw.sound);
final Button b = (Button) findViewById(R.id.Button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
}
}
This was all we had to do
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
}
The best way to do this is here i found after searching for one issue after other in the LogCat
MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
Not releasing the Media player gives you this error in LogCat:
Android: MediaPlayer finalized without being released
Not resetting the Media player gives you this error in LogCat:
Android: mediaplayer went away with unhandled events
So play safe and simple code to use media player.
To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like
mp = MediaPlayer.create(context, R.raw.sound_two);
and play it !
Have fun!
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
Button one;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.soho);
one = (Button)this.findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
}
});
}
}
The audio must be placed in the raw folder, if it doesn't exists,
create one.
The raw folder must be inside the res folder
The name mustn't have any - or special characters in it.
On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.
Example:
private Button myButton;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mp = MediaPlayer.create(this, R.raw.gunshot);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
}
there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.
Nice!
MediaActionSound
A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs
use like:
fun playBeepSound() {
val sound = MediaActionSound()
sound.play(MediaActionSound.START_VIDEO_RECORDING)
}
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MediaPlayer mp1 = MediaPlayer.create(this, R.raw.b1);
mp1.start();
}
});
Try this i think it will work
public class MainActivity extends AppCompatActivity {
public void clickMe (View view) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
mp.start();
}
create a button with a method could be called when the button pressed (onCreate),
then create a variable for (MediaPlayer) class with the path of your file
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
finally run start method in that class
mp.start();
the file will run when the button pressed, hope this was helpful!
Instead of resetting it as proposed by DeathRs:
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
we can just reset the MediaPlayer to it's begin using:
if (mp.isPlaying()) {
mp.seekTo(0)
}
An edge case: Above every answer is almost correct but I was stuck in an edge case. If any user randomly clicks the button multiple times within a few seconds then after playing some sound it doesn't respond anymore.
Reason: Initialize Mediaplayer object is very expensive. It also deals with resources (audio file) so it takes some time for it. When users randomly initialize and calling a method of MediaPlayer's methods like start(), stop(), release(), etc can cause IllegalStateException which I faced.
Solution: Thanks caw for his suggestion in the comment about Android-Audio.
It has just a simple two java classes (MusicManager.java, SoundManager.java).
You can use MusicManager.java if you want to play one-off sound files -
MusicManager.getInstance().play(MyActivity.this, R.raw.my_sound);
You can use SoundManager.java if you want to play multiple sounds frequently and fast -
class MyActivity extends Activity {
private SoundManager mSoundManager;
#Override
protected void onResume() {
super.onResume();
int maxSimultaneousStreams = 3;
mSoundManager = new SoundManager(this, maxSimultaneousStreams);
mSoundManager.start();
mSoundManager.load(R.raw.my_sound_1);
mSoundManager.load(R.raw.my_sound_2);
mSoundManager.load(R.raw.my_sound_3);
}
private void playSomeSound() {
if (mSoundManager != null) {
mSoundManager.play(R.raw.my_sound_2);
}
}
#Override
protected void onPause() {
super.onPause();
if (mSoundManager != null) {
mSoundManager.cancel();
mSoundManager = null;
}
}
}
In Java:
private void playBeepSound(){
MediaActionSound sound = new MediaActionSound();
sound.play(MediaActionSound.START_VIDEO_RECORDING);
}
All these solutions "sound" nice and reasonable but there is one big downside. What happens if your customer downloads your application and repeatedly presses your button?
Your MediaPlayer will sometimes fail to play your sound if you click the button to many times.
I ran into this performance problem with the MediaPlayer class a few days ago.
Is the MediaPlayer class save to use? Not always. If you have short sounds it is better to use the SoundPool class.
A save and efficient solution is the SoundPool class which offers great features and increases the performance of you application.
SoundPool is not as easy to use as the MediaPlayer class but has some great benefits when it comes to performance and reliability.
Follow this link and learn how to use the SoundPool class in you application:
https://developer.android.com/reference/android/media/SoundPool
Youtube: Save Solution
check if mp != null then use the current function:
MediaPlayer mpClick;
private void onClickSound() {
if(mpClick == null){
mpClick = MediaPlayer.create(context,R.raw.tap);
}
if(mpClick.isPlaying())
{
}
else
{
mpClick.start();
}
}
usage:
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
onClickSound();
}
});

Losing the control of the mediaplayer when the activity is recreated

In my project I am trying to make a media player which plays a shoutcast stream. Everything seemed to be working well until I pressed the back button on my device, which I think stops the activity and causes the device to recreate the activity when launched again. The problem is , when the activity is recreated , I lose the control of the mediaplayer and a new mediaplayer is created.
I need to be able to have the mediaplayer's control back at that point. How is it possible?
This part of code belongs to onCreate
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
if (mediaPlayer == null){
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getString(R.string.yayin));
} catch (Exception e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
}
if(!isPlaying){
btn.setBackgroundResource(R.drawable.oynat);
}
else{
btn.setBackgroundResource(R.drawable.durdur);
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isPlaying){
playOnReady();
isPlaying = true;
btn.setBackgroundResource(R.drawable.durdur);
}
else{
mediaPlayer.reset();
isPlaying = false;
btn.setBackgroundResource(R.drawable.oynat);
}
}
});
This part of code belongs to the function playOnReady()
private void playOnReady(){
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
Take a look at the Android Activity lifecycle flowchart: https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You need to account for the path where onPause is called when you leave the Activity and then onResume is called when you enter it again. The solution for you could be as simple as moving some/all of your code from onCreate into onResume.
Using this tutorial I have managed to build a service which handles the mediaplayer that I can have the control of anytime I need.

Android MediaPlayer not stopping by clicking alternate button

I have an MediaPlayer with many Sounds. Here is my app in Google Play store: https://play.google.com/store/apps/details?id=de.logtainment.ungesoundboard. Note: the app is in German. When you click on two buttons you hear two sounds. How can I stop the first sound and play the second sound or when I play the first sound, that the second sound stops? How can I create this? Here my Media Player code:
public class SoundsZweiActivity extends ActionBarActivity {
Toolbar toolbar;
MediaPlayer runtergeholt;
//This is When I click on The button
public void runtergeholt(View paramView) {
this.runtergeholt.start();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sounds_zwei);
//MediaPlayer
this.runtergeholt = MediaPlayer.create(this, R.raw.runtergeholt);
//Toolbar
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
I hope the Community help me!
I've downloaded your app and, made a quick implementation of how I would do it with 3 Buttons, since I've noticed your bad english I also commented important parts in german :
EDIT : Thanks to #Trinimon heres an even cleaner solution with just one MediaPlayer :
// implement View.OnClickListener :
public class SoundZweiActivity extends ActionBarActivity implements View.OnClickListener {
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sounds_zwei);
createButtons();
}
private void createButtons() {
// put your Buttons in an Array and set OnClickListener on all
Button[] buttons = new Button[]{
(Button) findViewById(R.id.btn_runtergeholt),
(Button) findViewById(R.id.btn_kranke_lache),
(Button) findViewById(R.id.btn_missgeburt),
// etc ...
};
for (Button button : buttons)
button.setOnClickListener(this);
}
private void createMediaPlayer(int id) {
// Here the MediaPlayer is killed and a new one created, I dont call .stop() and then
// .start() again because it often crashes when the mediaPlayer is not prepared yet,
// for example when clicking different Buttons really fast
// Hier wird der MediaPlayer zerstört
// und ein neuer erschaffen, wenn man .stop() und wieder .start() ruft kommt es vor dass
// der MediaPlayer noch nicht bereit ist, falls man z.B. ganz schnell
// hintereinander verschiedene Tasten drückt stürzt er oft ab
if (mediaPlayer != null)
mediaPlayer.release();
mediaPlayer = MediaPlayer.create(this, id);
mediaPlayer.start();
}
#Override
public void onClick(View v) {
// Determine which button is clicked and play its sound
// Hier wird gecheckt welcher Knopf gedrückt wurde und der dazugehörige Sound gespielt
switch (v.getId()) {
case R.id.btn_runtergeholt:
createMediaPlayer(R.raw.runtergeholt); // plays first sound (runtergeholt)
break;
case R.id.btn_kranke_lache:
createMediaPlayer(R.raw.kranke_lache); // plays second sound (kranke_lache)
break;
case R.id.btn_missgeburt:
createMediaPlayer(R.raw.missgeburt);// plays third sound (missgeburt)
break;
// etc ...
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// kill mediaPlayer
if (mediaPlayer != null)
mediaPlayer.release();
}
}
You could simply do thisfirstmediaplayer.stop();after start the Mediaplayer runtergeholt.
I'd add an OnCompletionListener, stop and release the player here as well:
runtergeholt.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) {
player.stop();
player.release();
...
}
Note: releasing the player is quite important, from the documentation: "... this method should be invoked to release the MediaPlayer object, unless the application has a special need to keep the object around. ..., failure to call this method immediately if a MediaPlayer object is no longer needed may also lead to continuous battery consumption for mobile devices, and playback failure for other applications if no multiple instances of the same codec are supported on a device."

Play sound on button click android

How do I get a button to play a sound from raw when click? I just created a button with id button1, but whatever code I write, all is wrong.
import android.media.MediaPlayer;
public class BasicScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
}
Button one = (Button)this.findViewById(R.id.button1);
MediaPlayer = mp;
mp = MediaPlayer.create(this, R.raw.soho);
zero.setOnCliclListener(new View.OnClickListener() )
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.basic_screen, menu);
return true;
}
}
This is the most important part in the code provided in the original post.
Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
To explain it step by step:
Button one = (Button) this.findViewById(R.id.button1);
First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById, passing the Id we assigned to it (in this example's case: R.id.button1), to get the button that we need. We cast it as a Button so that it is easy to assign it to the variable one that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
This is how to initialize a MediaPlayer. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create() method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho. We declare it as final. Jon Skeet provided a great explanation on why we do so here.
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//code
}
});
Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener of our button one. Inside is only one method, onClick() which contains what instructions the button should do on click.
public void onClick(View v) {
mp.start();
}
To play the sound, we call MediaPlayer's start() method. This method starts the playback of the sound.
There, you can now play a sound on button click in Android!
Bonus part:
As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release() method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener to our mp like so:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//code
}
});
Inside the onCompletion method, we release it like so:
public void onCompletion(MediaPlayer mp) {
mp.release();
}
There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment or Activity that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.
Original Post
First. You should put your statements inside a block, and in this case the onCreate method.
Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.
Third, put the logic to play the sound inside the onClick.
In summary:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BasicScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
}
}
Tested and working 100%
public class MainActivity extends ActionBarActivity {
Context context = this;
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mp = MediaPlayer.create(context, R.raw.sound);
final Button b = (Button) findViewById(R.id.Button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
}
}
This was all we had to do
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
}
The best way to do this is here i found after searching for one issue after other in the LogCat
MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
Not releasing the Media player gives you this error in LogCat:
Android: MediaPlayer finalized without being released
Not resetting the Media player gives you this error in LogCat:
Android: mediaplayer went away with unhandled events
So play safe and simple code to use media player.
To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like
mp = MediaPlayer.create(context, R.raw.sound_two);
and play it !
Have fun!
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
Button one;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.soho);
one = (Button)this.findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
}
});
}
}
The audio must be placed in the raw folder, if it doesn't exists,
create one.
The raw folder must be inside the res folder
The name mustn't have any - or special characters in it.
On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.
Example:
private Button myButton;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mp = MediaPlayer.create(this, R.raw.gunshot);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
}
there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.
Nice!
MediaActionSound
A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs
use like:
fun playBeepSound() {
val sound = MediaActionSound()
sound.play(MediaActionSound.START_VIDEO_RECORDING)
}
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MediaPlayer mp1 = MediaPlayer.create(this, R.raw.b1);
mp1.start();
}
});
Try this i think it will work
public class MainActivity extends AppCompatActivity {
public void clickMe (View view) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
mp.start();
}
create a button with a method could be called when the button pressed (onCreate),
then create a variable for (MediaPlayer) class with the path of your file
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
finally run start method in that class
mp.start();
the file will run when the button pressed, hope this was helpful!
Instead of resetting it as proposed by DeathRs:
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
we can just reset the MediaPlayer to it's begin using:
if (mp.isPlaying()) {
mp.seekTo(0)
}
An edge case: Above every answer is almost correct but I was stuck in an edge case. If any user randomly clicks the button multiple times within a few seconds then after playing some sound it doesn't respond anymore.
Reason: Initialize Mediaplayer object is very expensive. It also deals with resources (audio file) so it takes some time for it. When users randomly initialize and calling a method of MediaPlayer's methods like start(), stop(), release(), etc can cause IllegalStateException which I faced.
Solution: Thanks caw for his suggestion in the comment about Android-Audio.
It has just a simple two java classes (MusicManager.java, SoundManager.java).
You can use MusicManager.java if you want to play one-off sound files -
MusicManager.getInstance().play(MyActivity.this, R.raw.my_sound);
You can use SoundManager.java if you want to play multiple sounds frequently and fast -
class MyActivity extends Activity {
private SoundManager mSoundManager;
#Override
protected void onResume() {
super.onResume();
int maxSimultaneousStreams = 3;
mSoundManager = new SoundManager(this, maxSimultaneousStreams);
mSoundManager.start();
mSoundManager.load(R.raw.my_sound_1);
mSoundManager.load(R.raw.my_sound_2);
mSoundManager.load(R.raw.my_sound_3);
}
private void playSomeSound() {
if (mSoundManager != null) {
mSoundManager.play(R.raw.my_sound_2);
}
}
#Override
protected void onPause() {
super.onPause();
if (mSoundManager != null) {
mSoundManager.cancel();
mSoundManager = null;
}
}
}
In Java:
private void playBeepSound(){
MediaActionSound sound = new MediaActionSound();
sound.play(MediaActionSound.START_VIDEO_RECORDING);
}
All these solutions "sound" nice and reasonable but there is one big downside. What happens if your customer downloads your application and repeatedly presses your button?
Your MediaPlayer will sometimes fail to play your sound if you click the button to many times.
I ran into this performance problem with the MediaPlayer class a few days ago.
Is the MediaPlayer class save to use? Not always. If you have short sounds it is better to use the SoundPool class.
A save and efficient solution is the SoundPool class which offers great features and increases the performance of you application.
SoundPool is not as easy to use as the MediaPlayer class but has some great benefits when it comes to performance and reliability.
Follow this link and learn how to use the SoundPool class in you application:
https://developer.android.com/reference/android/media/SoundPool
Youtube: Save Solution
check if mp != null then use the current function:
MediaPlayer mpClick;
private void onClickSound() {
if(mpClick == null){
mpClick = MediaPlayer.create(context,R.raw.tap);
}
if(mpClick.isPlaying())
{
}
else
{
mpClick.start();
}
}
usage:
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
onClickSound();
}
});

Android : stop and play sound on button click

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);
}
}

Categories

Resources