Android Mediaplayer不会停止

时间:2013-10-03 10:05:01

标签: android button audio

我有以下代码从网上播放mp3文件,这是有效的,但当我使用停止功能时,音频不会停止。任何人都可以指向我寻找更多有关这方面的资源或告诉我哪里出错了?感谢。

showAudio.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        if (!showAudio.getText().equals("Stop")) {
            try {
                String url = lblAudio.getText().toString();
                if (url.length() > 2) {
                    mediaPlayer.setDataSource(url);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    showAudio.setText("Stop");
                }
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), "Sorry, there was a problem playing audio.", Toast.LENGTH_SHORT).show();
            }
        } else {
            try {
                mediaPlayer.stop();
                mediaPlayer.release();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            showAudio.setText("Audio");
        }
    }
});

4 个答案:

答案 0 :(得分:2)

每次单击按钮时,您都在创建新的MediaPlayer。在点击处理程序之外创建播放器。

答案 1 :(得分:0)

试试:

 try { 
     if(mediaPlayer.isPlaying())
      {
       mediaPlayer.stop();
       mediaPlayer.release(); 
       }
       } catch(Exception ex) { 
             ex.printStackTrace();
        }

答案 2 :(得分:0)

尝试将您的媒体播放器设为全局变量,并将其设为静态....

答案 3 :(得分:0)

我有一个可以启动和停止的工作媒体播放器

Uri ringtone;
MediaPlayer mp;

ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        mp = MediaPlayer.create(getApplicationContext(), ringtone);

    //code to start the mediaplayer

     if (Flags.notificationReceived) {
                        showAlert(Flags.patientModel);
                        Flags.notificationReceived = false;
                        mp.start();
                        mp.setLooping(true);
                        vibrate(2000);
                    }

    //code to stop the media player

     if (mp.isPlaying()) {
                        mp.stop();
                        mp.reset();
                        mp.release();
                        mp = MediaPlayer.create(getApplicationContext(), ringtone);


   }