Hey I created a Soundboard with 200 Sounds but when I click a lot on the buttons the MediaPlayer stops working although I clean up the MediaPlayer.
Here is the code with only 2 Sounds:
public class MainActivity extends AppCompatActivity{
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//plays sound
public void sound1(View view){
cleanUpMediaPlayer();
mp = MediaPlayer.create(this, R.raw.sound1);
mp.start();
}
public void sound2(View view){
cleanUpMediaPlayer();
mp = MediaPlayer.create(this, R.raw.sound2);
mp.start();
}
public void cleanUpMediaPlayer(){
if(mp != null) {
if(mp.isPlaying()) {
try {
mp.reset();
mp.prepare();
mp.stop();
mp.release();
mp = null;
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}
What is wrong with this Code? And why does my MediaPlayer stops working after approximately 80 clicks.
Related
I have two buttons and two songs. If I click the first button, the first sound plays. But if I click the second button while the first sound is playing the second sound starts playing too.
How can I stop other sounds?
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer johnCenaPlayer = MediaPlayer.create(this, R.raw.john_cena);
Button johnCenaButton = (Button) findViewById(R.id.john_cena_button);
johnCenaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
johnCenaPlayer.start();
}
});
final MediaPlayer haGayPlayer = MediaPlayer.create(this, R.id.ha_gay_button);
Button haGayButton = (Button) findViewById(R.id.ha_gay_button);
haGayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
haGayPlayer.start();
}
});
}
Stop the other MediaPlayer in clickListener using stop() method.
public void onClick(View view) {
ha_gay.stop()
john_cena.start();
}
If you have many audio files use a single MediaPlayer and change the sources dynamically.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mediaPlayer = new MediaPlayer();
Button john_cena_button = (Button) findViewById(R.id.john_cena_button);
john_cena_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopAndPlay(R.raw.john_cena, mediaPlayer);
}
});
Button ha_gay_button = (Button) findViewById(R.id.ha_gay_button);
ha_gay_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopAndPlay(R.raw.ha_gay, mediaPlayer);
}
});
}
// This resets the mediaPlayer and starts the given audio
private void stopAndPlay(int rawId, MediaPlayer mediaPlayer) {
mediaPlayer.reset();
AssetFileDescriptor afd = this.getResources().openRawResourceFd(rawId);
try {
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
Try this one. Do it same for the other.
final MediaPlayer john_cena = MediaPlayer.create(this, R.raw.john_cena);
Button john_cena_button = (Button) findViewById(R.id.john_cena_button);
john_cena_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (he_gay.isPlaying()){
he_gay.stop();
}
else if (john_cena.isPlaying()){
john_cena.seekTo(0);
} else{
john_cena.start();
}
}
});
i'm the newbie this my code
the sound is not play but when i click the button the toast is show
anyone help me??
public class DB_Parse extends Activity {
MediaPlayer mp;
Button button;
int ,sound;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.keterangan);
final int sound = iIdentifikasi.getIntExtra("dataID", 0);
button=(Button)findViewById(R.id.btnsound);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (sound==1){
mp = MediaPlayer.create(getApplicationContext(), R.raw.munfasil);
mp.start();
}
Toast.makeText(getApplicationContext(),
"Sound is Play", Toast.LENGTH_LONG).show();
}
});
}
}
if (sound==1) 1 from _id in sqlite
try this way it will work
public class DB_Parse extends Activity {
private static final String TAG = "MyActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG, "Initializing sounds...");
final MediaPlayer mp = MediaPlayer.create(this, R.raw.youraudio);
Button play_button = (Button)this.findViewById(R.id.play_button);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
Log.v(TAG, "Sounds initialized.");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Put your audio/media file in asset folder instead putting into raw folder and follow above snippet, its working quite fine for me..
try
{
AssetFileDescriptor afd = getAssets().openFd("your_media_file_name.mp3");
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch(Exception e)
{ e.printStackTrace();}
Fire it on your button click event
First of all you are declaring your variable sound twice.
Please change:
final int sound = iIdentifikasi.getIntExtra("dataID", 0);
for
sound = iIdentifikasi.getIntExtra("dataID", 0);
The other thing that you should try is changing the toast inside your if, so you are sure that sound is 1.
if (sound==1){
mp = MediaPlayer.create(getApplicationContext(), R.raw.munfasil);
mp.start();
Toast.makeText(getApplicationContext(),
"Sound is Play", Toast.LENGTH_LONG).show();
}
If toast is not displaying your int sound is not 1.
I have started a sound in onCreate method meaning when I open the app the music starts playing. Then I have a button to stop the music and it's ok. But if I start the app then leave the app the music stills playing so I want to stop the music too when I click the back button to leave the app.
I have this code:
onCreate:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.seconds);
mp.start();
Then onDestroy:
#Override
public void onDestroy()
{
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
mp.stop;
}
But in mp.stop; i have mp in red so isn't working.
If i try to put MediaPlayer mp outside onCreate then the mp.start; and mp.stop; mp turn blues and don't work too.
Any advice?
public class ExampleActivity extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//other codes
mp = MediaPlayer.create(this, R.raw.seconds);
mp.prepare();
mp.start();
}
protected void onDestroy() {
//other codes
mp.stop();
}
}
try to use like above..
You can play song using this function
public void playSong()
{
try
{
mp.reset();
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Then on destroy just release the player
#Override
public void onDestroy(){
super.onDestroy();
mp.release();
}
try this
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
///
mp = MediaPlayer.create(this, R.raw.seconds);
}
#Override
protected void onStop() {
if(mp.isPlaying()){
mp.stop();
}
super.onStop();
}
put following code in Activity's onStop() method so that when your activity goes in backstack or you leave the app, the music will be stopped.
#Override
protected void onStop()
{
if(mp != null && mp.isPlaying())
{
mp.stop();
mp.release();
mp = null;
}
super.onStop();
}
public class SampleMediaPlayer extends Activity {
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_media_player); //your layout resource
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
mediaPlayer.release();
mediaPlayer = null;
}
}
I want to develop media player type of application which has two button one for play and pause and one for stop. I take two image buttons in my layout file and reference it in Java file and code like this which I put here, but when I click on stop button audio is getting stopped but then I want replay audio file; but I cant play with play button.
my Java code below
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
mp = MediaPlayer.create(getActivity(), R.raw.arti);
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
Use This:
private BackgroundSound mBackgroundSound;
private MediaPlayer player;
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
player = MediaPlayer.create(HomePage.this, R.raw.background);
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
player.setLooping(true); // Set looping
player.setVolume(volume, volume);
player.start();
return null;
}
}
For Playing:
mBackgroundSound = new BackgroundSound();
mBackgroundSound.execute();
For Stop:
mBackgroundSound.cancel(true);
if (player != null) {
player.stop();
player.release();
}
For Pause:
if (player != null) {
player.pause();
}
Try this it will help you....
//Click Listener on Image Button with play and Pause method
PLAY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Play-Pause();
}
});
//Play Pause method...........
public void Play-Pause(){
if (mediaPlayer.isPlaying()) {
PLAY.setImageResource(R.drawable.pause);
mediaPlayer.pause();
} else {
PLAY.setImageResource(R.drawable.play);
mediaPlayer.start();
}
}
Once a media player is stopped, you need to call prepare on it again to get it to a state where you can call start(). Look at the state diagram here http://developer.android.com/reference/android/media/MediaPlayer.html#pause%28%29
Check this code, its better and simple solution !
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
Switch sw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this,R.raw.nokia);
sw = findViewById(R.id.sw);
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mp.setLooping(true);
}
});
}
public void play(View v){
mp.start();
}
public void pause(View v){
if(mp.isPlaying())
mp.pause();
}
public void stop(View v){
if(mp.isPlaying()) {
boolean loop=mp.isLooping();
mp.stop();
mp = MediaPlayer.create(this, R.raw.nokia);
mp.setLooping(loop);
}
}
}
HELP please this is just a simple android app I am developing, it's meant to play a sound every time you click the button....it works when I click the button at a slow pace, but always crashes if I click the button at a fast pace due to a runtime error - NullPointerException!.....I don't know what I am doing wrong.
THIS IS MY CODE
public class Main extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button e = (Button) findViewById(R.id.Button1);
e.setOnClickListener(this);
}
public void onClick(View v){
if(v.getId()==R.id.imageButton1){
final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);
i.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
i.release();
}
});
i.start();
}
}
}
Its only a guess but in the documentation here you will find the following
public static MediaPlayer create (Context context, int resid)
...
Returns a MediaPlayer object, or null if creation failed
This means you should make sure that the line
final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);
does not return a null.
Edit:
Im really not sure how to handle the situation if create(Context context, int resid) is failing. But you have to do, because it is even from the documentation very clear that it can happen.
To be sure this is really the problem just ignore this case and return from your handler.
For example...
public void onClick(View v)
{
if(v.getId() == R.id.imageButton1)
{
final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);
if (i != null)
{
...
i.start();
}
}
}
Try it this way....
public class Blah extends Activity implements OnClickListener {
MediaPlayer mp;
#Override
public void onCreate(Bundle b)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button e = (Button) findViewById(R.id.Button1);
mp = MediaPlayer.create(R.raw.match);
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
i.release();
}
});
e.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.seekTo(0);
mp.start();
}
});
}
}
I had the same problem
my solution was to re-encode the mp3 files with the LAME mp3 encoder
You can use this program: http://www.freac.org/index.php/en/downloads-mainmenu-33
apparently android is quite picky about mp3 codecs