开发者

Pause MediaPlayer when using a Map in android app

I am building a soundboard with about 40 sounds using a map. (Previous thread)

Does anyone know a good way to pause restart Mediaplayer if the app is moved to the background (incoming call or anything like that)? I'm still very new at this so it is probably something super simple. Thanks anyone who can help.

Map map = new

HashMap();

map.put(R.id.button1, R.raw.sound1);

map.put(R.id.button2, R.ra开发者_如何学Cw.sound2);

...

and then iterate:

for (Map.Entry entry : map.entrySet()) {

final MediaPlayer sound = MediaPlayer.create(entry.getValue());

Button button = (ImageButton) findViewById(entry.getKey());

button.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

        sound.start();

    }

}); 

}


I assume you don't want to play all sounds together, so you can declare the mediaplayer object outside the loop and then you don't need to know which file is being played. You can use sound.pause(); sound.stop(); or sound.reset(); (depends on the action you want to preform) I suggest you look at the android docs to see how to implement it properly.

If you want to create mediaplayer for each file which I doubt you want, save the mediaplayers in a map / list and pause / reset them in loop during onPause().


Override Activity.onPause(). This is called whenever your app goes to the background, Home button or back button or incoming call or magic thunderclouds of doom.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜