0

我现在正在制作一个应用程序,它根据我按下的按钮播放声音,问题是我有 100 个按钮和 100 种不同的声音,过了一会儿它会破坏内存并崩溃给我 (-19,0) 错误是我的代码,你能告诉我如何避免这种情况吗?谢谢

 package com.example.buttonsdemo;

    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.app.Activity;
    import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends Activity implements View.OnClickListener{

        //Creating Sound arrays 
        MediaPlayer[] mediaplayer = new MediaPlayer[200];
        int i = 0;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);



            //Creating Button Array
            Button button[] = new Button [200]; 
            mediaplayer[1]= MediaPlayer.create(this,R.raw.alistar);
            mediaplayer[0]= MediaPlayer.create(this,R.raw.akali);






            button[i].setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    switch(v.getId())
                    {

                case R.id.akali:
                                        i=0;
                    break;
                case R.id.alistar:
                    i=1;
                    break;
                            }
mediaplayer[1].start(); 
                }
            } );








    }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }




    }

编辑:我试图让它更通用,所以我只调用 1 .start();

4

1 回答 1

0

首先,您可能应该使用 AndroidListView作为您的点击目标,而不是一个巨大Array的点击目标Buttons。这将为您节省大量内存。其次,您应该使用诸如 soundPool 之类的东西,而不是使用大量的 MediaPlayers。如果该路线对您来说没有吸引力,您需要为每次点击创建一个 MediaPlayer,然后将其丢弃。沿着这些思路的一个简单解决方案如下所示:

主类:

class MyActivity {
  private MediaPlayer mMediaPlayer;
  private HashMap<Integer, Integer> soundMap;
  private ListView mListView;
  private ArrayAdapter<Integer> mAdapter;

  @Override
  onCreate(Bundle savedInstanceState) {
    mAdapter = new MySimpleSoundAdapter();

    int[] sounds = {R.raw.alistar, R.raw.alkili, /*...*/ };

    mListView = findViewById(R.id.listView);
    mListView.setAdapter(new ArrayAdapter<Integer>(this, R.layout.textview, sounds));
    mListView.setOnItemClickListener(new OnItemClickListener() {
      @Override
      void onItemClick (AdapterView<?> parent, View view, int position, long id) {
        MediaPlayer mp = 
            MediaPlayer.create(MyActivity.this, (int) mAdapter.getItem(position);
        mp.start(); 
      }
    });
  }
}    
于 2013-03-05T01:45:12.153 回答