MediaPlayer and map issues android app (noob question)
I'm just learning here. I'm trying to make a soundboard 开发者_JAVA技巧with around forty sounds, but I'm having some trouble how to get it to work using a maphash. Can anyone save me?
--------------soundboard-------------------------
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import java.util.HashMap;
import java.util.Map;
public class main extends Activity {
MediaPlayer mp=null;
\\\if I put put "MediaPlayer mp;" here it only plays one sound\\\
ImageButton Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(R.id.button1, R.raw.sound1);
map.put(R.id.button2, R.raw.sound2);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
mp = MediaPlayer.create(this, entry.getValue());
\\\if I put "final MediaPlayer mp = MediaPlayer.create(this, entry.getValue());" here I cant stop MediaPlayer with onpause and onstop overrides.\\\
ImageButton button = (ImageButton) findViewById(entry.getKey());
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
}
}
@Override
protected void onStop() {
super.onStop();
if(mp.isPlaying()){
mp.stop();
mp.release();
}
}
@Override
public void onDestroy(){
super.onDestroy();
mp.release();
}
}
As I suggested in your previous question, don't create all those mediaplayer instances, for two reasons:
- You lose all instances and have only the last one. always.
- The onCreate() become very long method for no reason.
instead, remove mp = MediaPlayer.create(this, entry.getValue());
from your for loop, and move it to inside of your listener, something like that (not tested...):
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int sound = map.get(v.getId());
mp = MediaPlayer.create(main.this, sound);
mp.start();
}
});
So you would create the mediaplayer instance only when needed.
BTW, main is not a good name for a class.
精彩评论