Pause MediaPlayer when using a Map in android app

早过忘川 提交于 2019-12-11 16:04:06

问题


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.raw.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();

    }

}); 

}


回答1:


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().




回答2:


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.



来源:https://stackoverflow.com/questions/5545593/pause-mediaplayer-when-using-a-map-in-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!