First of all, I'm new to Java. Second, my intents here are as follows:
User clicks button (playPause) -> button toggles to pause drawable (pause1) and stream begins and user clicks button -> stream pauses and button toggles to play drawable(play1).
Now my problem is how to implement this behavior, an onClick method, inside of the current method playPauseMusic which contains an onPrepared method that is used to prepare the MediaPlayer asynchronously.
My intuition is to make a check for isPlaying and toggle from there, but my attempts so far have ended in failure.
Here is the relevant code and thank you for your time:
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);
}
}
I hope this helps.
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);
}
}
Related
I'm new in android development and I really can't figure out how to do that. So, I'm building an android app that stream music online via url. There is an url that shows current song. here is the url
I created a textView in my activity_main file to put current song text inside it, but I can't figure out how. I understand that I need to make variable url, then I need to parse that URL and put it inside text view. Or not?
Here is my MainActivity.java:
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView currentSong;
private boolean playPause;
private MediaPlayer mediaPlayer;
private boolean initialStage = true;
private ProgressBar pgsBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.audioStreamBtn);
currentSong = (TextView) findViewById(R.id.currentSong);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
pgsBar = findViewById(R.id.progressBar);
pgsBar.setVisibility(View.GONE);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
btn.setText("Stop");
if (initialStage) {
new Player().execute("stream url ...");
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = true;
} else {
btn.setText("Play");
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
playPause = false;
}
}
});
}
class Player extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
Boolean prepared = false;
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
initialStage = true;
playPause = false;
btn.setText("Play");
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
prepared = true;
} catch (Exception e) {
prepared = false;
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (pgsBar.getVisibility() == View.VISIBLE) {
pgsBar.setVisibility(View.GONE);
btn.setEnabled(true);
}
mediaPlayer.start();
initialStage = true;
}
#Override
protected void onPreExecute() {
mediaPlayer.reset();
super.onPreExecute();
pgsBar.setVisibility(View.VISIBLE);
btn.setEnabled(false);
}
}
}
How do I pull out this text and put it in my textView "currentSong"?
You can use okHttp library to make a network request to URL and it will get back the response as string. Modify the response according to your liking and use that value for setText() of text view .
Use Retrofit or Volley to make a URL request.
possible duplicate of Make an HTTP request with android
I'm new to Android and Java development. I'm trying to make an app that plays an Icecast audio stream.
I found, copied and edited the below code into a class called Audio Stream
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.io.IOException;
public class AudioStream extends Activity implements OnClickListener {
private Button buttonPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
Log.d("Classloaded", "Class loaded");
}
private void initializeUIElements() {
buttonPlay = findViewById(R.id.PlayPauseButton);
buttonPlay.setOnClickListener(this);
}
public void onClick(View v) {
Log.d("onClick", "On Click worked");
if (v == buttonPlay) {
startPlaying();
}
}
private void startPlaying() {
buttonPlay.setEnabled(false);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("streamURL");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
When I run the app the neither of the Log.d events fire off so I can only assume the class is never loaded and instanced. So I added the tried the following in MainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioStream stream = new AudioStream();
}
}
I know I'm doing something wrong. How do I get the AudioStream class to instance when the app loads so that the OnClickListener will work when I press the play button?
Instead of :
public void onClick(View v) {
Log.d("onClick", "On Click worked");
if (v == buttonPlay) {
startPlaying();
}
}
you should do like :
public void onClick(View v) {
Log.d("onClick", "On Click worked");
if (v.getId == R.id.PlayPauseButton) {
startPlaying();
}
}
I tried a lot with my code below . there is no compile error at all. when I used to start the MP3 which I added , in the logcat window it shows "start called in state 0". please help me with this code . Thanks in advance .I also want to know when we pause the audio , i need to get the song resume from there when i click the start button (or) Is there any resume function for it , Let me know in the comments section . Thanks in advance. Here's my Java code
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.btnStart);
Button mButton1 = (Button) findViewById(R.id.btnStop);
Button mButton2 = (Button) findViewById(R.id.btnPause);
mp = new MediaPlayer();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
mButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
}
});
mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer.create(MainActivity.this, R.raw.ch);
mp.pause();
}
});
create a class named AudioClip
public class AudioClip {
public static boolean loop = false;
public static MediaPlayer mediaPlayer;
private static SoundPool soundPool;
public static boolean isplayingAudio = false;
public static void playAudio(Context c, int id) {
mediaPlayer = MediaPlayer.create(c, id);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
if (!mediaPlayer.isPlaying()) {
isplayingAudio = true;
mediaPlayer.start();
mediaPlayer.setLooping(loop);
}
}
public static void stopAudio() {
isplayingAudio = false;
mediaPlayer.stop();
}
}
on other activity to play music
Context m = CuteActivity.this;
AudioClip.playAudio(m, R.raw.ch);\
and to stop
if (AudioClip.isplayingAudio) {
AudioClip.stopAudio();
}
I am a newbie in android app development. For now my challenge is to add two buttons in my UI one for playing an mp3 file and the other for stopping it. I am able to do the first successfully and as I try to do the stop one, I see no result. My code is as following:
package ir.polyglotcenter.childrenmostfrequentwords;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button myButtonOne = (Button) findViewById(R.id.btn_audio);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer media = MediaPlayer.create(Main.this, R.raw.audio);
media.start();
}
});
//this is to stop the audio flow
Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer media = MediaPlayer.create(Main.this, R.raw.audio);
media.stop();
}
});
}
}
Try this code:
public class Main extends Activity {
protected MediaPlayer mMediaPlayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMediaPlayer = MediaPlayer.create(Main.this, R.raw.audio);
Button myButtonOne = (Button) findViewById(R.id.btn_audio);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mMediaPlayer.prepare();
mMediaPlayer.start();
}
});
//this is to stop the audio flow
Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mMediaPlayer.isPlaying())
mMediaPlayer.stop();
}
});
}
}
Play and Stop all song for all rows.
The Point is implement MediaPlayer in the loop of if or any loop you have:
if(playandstop==true){
mp=MediaPlayer.create(MainActivity.this, resourceIIIDD);
mp.start();
playandstop=false;
}else{
mp.stop();
playandstop=true;
}
so i have this code to stream an mp3, now i was wondering how can i make the music stop when someone exits the app with the back button/home button. Even if i exit the app and close it the music is still playing in the background and i have no way to make it stop.
package com.hrupin.streamingmedia;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import com.hrupin.media.R;
public class StreamingMp3Player extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
public EditText editTextSongURL;
private MediaPlayer mediaPlayer;
private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
private final Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
/** This method initialise all the views in project*/
private void initView() {
buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
//editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
//editTextSongURL.setText(R.string.testsong_20_sec);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.ButtonTestPlayPause){
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource("http://www.metalgeardroid.com/music/OST.mp3"); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.button_pause);
}else {
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.button_play);
}
primarySeekBarProgressUpdater();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.SeekBarTestPlay){
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if(mediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
buttonPlayPause.setImageResource(R.drawable.button_play);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
seekBarProgress.setSecondaryProgress(percent);
}
}
Override the onPause() method
#Override
public void onPause() {
if( mediaPlayer.isPlaying() ) {
mediaPlayer.stop();
}
super.onPause();
}
This method is called when the user leaves your app via the back button, home button, or if they launch another app (via notification etc)
Override the onBackPressed method and stop the player.
#Override
public void onBackPressed() {
if( mediaPlayer.isPlaying() ) {
mediaPlayer.stop();
}
super.onBackPressed();
}