Android声音只播放一次

时间:2013-06-18 18:43:05

标签: java android audio

我在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;
}

}  

我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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();

        }
    });