首先,我是Java的新手。其次,我的意图如下:
用户点击按钮(playPause
) - >按钮切换为暂停可绘制(pause1
),流开始和用户点击按钮 - >流暂停和按钮切换以播放drawable(play1
)。
现在我的问题是如何在当前方法onClick
内部实现此行为,playPauseMusic
方法,其中包含用于异步准备MediaPlayer的onPrepared
方法。 / p>
我的直觉是检查isPlaying
并从那里切换,但到目前为止我的尝试都以失败告终。
以下是相关代码,感谢您的时间:
radio.java
package com.example.jacob.wutk;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import java.io.IOException;
public class radio extends AppCompatActivity {
/** Called when the user touches the button */
public void playMusic(View view) throws IOException {
String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer){
mediaPlayer.start();
}
});
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
}
}
答案 0 :(得分:0)
我希望这会有所帮助。
public class radio extends AppCompatActivity {
MediaPlayer mediaPlayer;
boolean prepared=false;
public void playMusic(View view) throws IOException {
playpause();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
mediaPlayer = new MediaPlayer();
String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis";
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer){
prepared=ture;
}
});
}
}
public void playPause() {
if (!mediaplayer.isPlaying()&&prepared) {
mediaplayer.start();
mediaplayer.setImageResource(R.drawable.ic_pause);
} else if(mediaplayer.isPlaying()) {
mediaplayer.pause();
mediaplayer.setImageResource(R.drawable.ic_play);
}
}