呼叫释放并播放多个声音

时间:2013-12-07 13:18:56

标签: android audio mp3 release

使用此代码我想停止正在执行的所有声音,并且仅播放单击的按钮,但是调用释放,声音变为空并且您无法再次运行声音。但如果你不打电话给我发送问题无论如何。我怎样才能找到这个难题的解决方案?

代码:

public MediaPlayer mediaPlayer = null;
    public Boolean playing = false;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

Button b1 = (Button)findViewById(R.id.b1);
b1.setOnClickListener(new Button.OnClickListener() { 

               public void onClick(View v){



                   if(mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();









                   mediaPlayer = MediaPlayer.create(menu.this, R.raw.b1);
                   mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            // TODO Auto-generated method stub

                            mediaPlayer.start();

                            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                                public void onCompletion(MediaPlayer mediaPlayer) {
                                    mediaPlayer.release();
                                    playing=true;
                                };
                            });

                                }
                            });


Button b2 = (Button)findViewById(R.id.b2);
    b2.setOnClickListener(new Button.OnClickListener() { 

               public void onClick(View v){


                   if(mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();

                   mediaPlayer = MediaPlayer.create(getBaseContext(),R.raw.b2);
                   mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            // TODO Auto-generated method stub

                            mediaPlayer.start();

                            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                                public void onCompletion(MediaPlayer mediaPlayer) {
                                    mediaPlayer.release();

                                };
                            });
                                }
                            });

               }});

1 个答案:

答案 0 :(得分:0)

我解决了这个问题:

b1.setOnClickListener(new Button.OnClickListener() { 

               public void onClick(View v){



                   if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
                       mediaPlayer.stop();
                       mediaPlayer.release();
                     }









                   mediaPlayer = MediaPlayer.create(menu.this, R.raw.b1);
                   mediaPlayer.start();

                }});