0

我是java的新手。所以程序应该接受用户输入的文本,如果有“a”它会播放a-sound,如果有“b”它会播放b-sound.并且它必须一个一个播放这个声音,即使有多个“a”或“b”。这是我的代码:

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button bStart = (Button) findViewById(R.id.bStart);
    final EditText etStart = (EditText) findViewById(R.id.etStart);
    final EditText etFinish = (EditText) findViewById(R.id.etFinish);
    final char[] arr = etStart.getText().toString().toCharArray();
    final MediaPlayer as = MediaPlayer.create(R2d2Activity.this, R.raw.as);
    final MediaPlayer bs = MediaPlayer.create(R2d2Activity.this, R.raw.bs);
    final SoundPool sp;
    final int a;
    final int b;
    final int t;
    sp = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
    a = sp.load(this, R.raw.as, 1);
    b = sp.load(this, R.raw.bs, 1);
    final String value = etStart.getText().toString();
    final Thread timer = new Thread(new Runnable() {
        @Override
        public void run() {
        try {
        Thread.sleep(1300);
        // Do some stuff
        } catch (Exception e) {
        e.getLocalizedMessage();
        }
        }
        });
    bStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int n = 0;
            String value;
            String first;
            value = etStart.getText().toString();
            // TODO Auto-generated method stub
                           //actual code
            for (int i=0; i<value.length(); i++){
                first = etStart.getText().toString().substring(i, i+1);
                if(first.contentEquals("a")){
                    as.start();
                    as.setOnCompletionListener(new OnCompletionListener(){
                        public void onCompletion(MediaPlayer arg0) {
                            //when finished


                             }
                    });

                        }else{
                            }
                if(first.contentEquals("b")){
                    bs.start();

                        }else{
                            }

            }



        }
    });

问题是它一次开始播放所有音频文件。我试图添加一些 OnCompletionListener,但我不知道如何处理它。请帮帮我。

4

1 回答 1

1

你能做的是

//define a variable to be used as index.
int audioindex = 0;
//Extract the files id into an array
int[] audioFileIds=new int[]{R.raw.as,R.raw.bs};

然后在你MediaPlayer onCompletionListener放的东西如下。

然后在您的 OnCompletionListener 中。

mp.setOnCompletionListener(new OnCompletionListener(){
    // @Override
    public void onCompletion(MediaPlayer player) {
    // File has ended, play the next one.
   FunctionPlayFile(audioFileIds[audioindex]);
   audioindex+=1; //increment the index to get the next audiofile
     }
});
于 2012-06-07T07:15:20.027 回答