我对Java很新,并且一直在开发一个应用程序来从Internet传输实时音频。除了暂停按钮,我已经完成了所有工作。它现在所做的只是在短时间内对音频进行加扰。我猜这与调用mediaPlayer.pause()
的地方有关,但我可能错了。感谢您的时间和回应。
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 playPauseMusic (View playPause) throws IOException {
String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis"; // your URL here
final MediaPlayer mediaPlayer = new MediaPlayer();
ImageButton imb = (ImageButton) findViewById(R.id.playPause);
if (mediaPlayer.isPlaying()) {
imb.setImageResource(R.drawable.play1);
mediaPlayer.pause();
return;
} else {
imb.setImageResource(R.drawable.pause1);
}
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 :(得分:1)
尝试使用此代码:
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 {
private MediaPlayer mediaPlayer;
private boolean isMediaPlayerStarted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
setMediaPlayer();
}
public void setMediaPlayer() {
try {
mediPlayer = new MediaPlayer();
String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis";
ImageButton imb = (ImageButton) findViewById(R.id.playPause);
imb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isMediaPlayerStarte) {
mediaPlayer.prepareAsync();
isMediaPlayerStarted = true;
} else {
if (mediaPlayer.isPlaying()) {
imb.setImageResource(R.drawable.play1);
mediaPlayer.pause();
} else {
imb.setImageResource(R.drawable.pause1);
mediaPlayer.start();
}
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}