0

我正在用java为android制作一个应用程序,每当点击一个按钮时,就会播放声音。它工作正常,但按下按钮一次使其播放,然后按下该按钮或任何其他按钮不会做任何事情。

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

Button s1, s2, s3, s4;
MediaPlayer ss1, ss2, ss3, ss4;

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

    s1 = (Button) findViewById(R.id.s1);
    s2 = (Button) findViewById(R.id.s2);
    s3 = (Button) findViewById(R.id.s3);
    s4 = (Button) findViewById(R.id.s4);

    s1.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            ss1 = MediaPlayer.create(MainActivity.this, R.raw.sound1);
            ss1.start();
        }
    });

    s2.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            ss2 = MediaPlayer.create(MainActivity.this, R.raw.sound2);
            ss2.start();
        }
    });

    s3.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            ss3 = MediaPlayer.create(MainActivity.this, R.raw.sound3);
            ss3.start();
        }
    });

    s4.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            ss4 = MediaPlayer.create(MainActivity.this, R.raw.sound4);
            ss4.start();
        }
    });



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}  

我怎样才能解决这个问题?

4

1 回答 1

2

你为什么不尝试这种方式
只使用一个MediaPlayer 并重复使用它。像这样的东西

    MediaPlayer ss1;
    s1 = (Button) findViewById(R.id.s1);
    s2 = (Button) findViewById(R.id.s2);
    s3 = (Button) findViewById(R.id.s3);
    s4 = (Button) findViewById(R.id.s4);


    s1.setOnClickListener(new View.OnClickListener(){       
           public void onClick(View v){
                ss1= new MediaPlayer();
                ss1= MediaPlayer.create(this, R.raw.sound1);
                ss1.prepare();
                ss1.start();

        }
    });
于 2013-06-18T18:53:08.923 回答