0

我有以下代码来播放网络上的 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

4 回答 4

3

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

于 2013-10-03T10:13:05.353 回答
0

试用 :

 try { 
     if(mediaPlayer.isPlaying())
      {
       mediaPlayer.stop();
       mediaPlayer.release(); 
       }
       } catch(Exception ex) { 
             ex.printStackTrace();
        }
于 2013-10-03T10:07:55.667 回答
0

尝试使您的媒体播放器成为全局变量并使其成为静态...。

于 2013-10-03T10:28:54.063 回答
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);


   }
于 2016-11-17T20:49:50.680 回答