I am doing an audio online streaming the audio is playing fine both in emulator and device. But the issue is when i make a call to my device simultaneously the streaming also playing. I need to pause and play the audio back while the call is coiming. Can u help how to handle that broadcasting.
public class BhajanStream extends Activity {
protected static final String TAG = null;
/** Called when the activity is first created. */
final String rs_bhajan_uri = "Media URL";
MediaPlayer mediaPlayer;
AudioManager audioManager;
Button bhajan_play;
Button bhajan_stop;
ImageView loadanim, effectbhajan;
AnimationDrawable loadanimation, effectanimation;
ProgressDialog dialog;
MusicServicePhoneStateListener mPhoneListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bhajan);
bhajan_play = (Button) findViewById(R.id.btn_play);
bhajan_stop = (Button) findViewById(R.id.btn_stop);
bhajan_stop.setVisibility(View.GONE);
loadanim = (ImageView) findViewById(R.id.loadeffectview);
effectbhajan = (ImageView) findViewById(R.id.bhajan_effect);
/*if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer= null;
}*/
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mediaPlayer.reset();
bhajan_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = conMan.getActiveNetworkInfo();
if (Info == null) {
Toast.makeText(BhajanStream.this, "POOR SIGNALS ",
Toast.LENGTH_LONG).show();
// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
loadanim.setBackgroundResource(R.drawable.loader_1);
loadanim.setBackgroundResource(R.anim.loadanim);
loadanimation = (AnimationDrawable) loadanim
.getBackground();
loadanimation.isVisible();
effectbhajan.setBackgroundResource(R.drawable.effect_bhajan1);
effectbhajan.setBackgroundResource(R.anim.bhajaneffect);
effectanimation = (AnimationDrawable) effectbhajan
.getBackground();
bhajan_play.setBackgroundResource(R.drawable.bhajan_start);
bhajan_play.setVisibility(View.GONE);
bhajan_stop.setVisibility(View.VISIBLE);
loadanim.setVisibility(View.VISIBLE);
effectbhajan.setVisibility(View.VISIBLE);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(rs_bhajan_uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
});
bhajan_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
bhajan_stop.setVisibility(View.GONE);
bhajan_play.setVisibility(View.VISIBLE);
mediaPlayer.stop();
loadanimation.stop();
effectanimation.stop();
loadanim.setVisibility(View.GONE);
effectbhajan.setVisibility(View.GONE);
}}
}
});
}
protected void onPreExecute() {
// UI work allowed here
loadanimation.start();
}
#Override
public void onBackPressed() {
// do something
if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
mediaPlayer.stop();
loadanimation.stop();
effectanimation.stop();
bhajan_stop.setVisibility(View.GONE);
bhajan_play.setVisibility(View.VISIBLE);
loadanim.setVisibility(View.GONE);
effectbhajan.setVisibility(View.GONE);
}
} else{
startActivity(new Intent(BhajanStream.this, SaiStreams.class));
finish();
}
}
private class MusicServicePhoneStateListener extends PhoneStateListener {
private boolean mResumeAfterCall = false;
#Override
public void onCallStateChanged(int state, String incoming_number) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
Log.i(TAG, "phone active, suspending music service");
mResumeAfterCall = mediaPlayer.isPlaying();
mediaPlayer.pause();
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i(TAG, "phone inactive, resuming music service");
if (mResumeAfterCall) {
mediaPlayer.start();
}
break;
default:
break;
}
}
}
public void onCreate(){
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public void onDestroy(){
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, 0);
}
}
In your activity,you can register a phone state listener by calling public void listen (PhoneStateListener listener, int events) in the TelephonyManager class. See here. Also,You can call Context.getSystemService(Context.TELEPHONY_SERVICE) to get an instance of the TelephonyManager object.
Related
I am developing an android app which play a mp3 songs by using a remote url. everything is working fine in android devices below api 5.0.But when starting app in samsung s5(5.1) it suddenly crashes
mu logcat is giving error "QCmediaPlayer mediaplayer is not present.Here is my code of Media Player
public class MainActivity2 extends Activity implements OnClickListener, OnPreparedListener {
private ProgressBar playSeekBar;
private final static String RADIO_STATION_URL ="https://aryaradio.s3.amazonaws.com/";
private String KEYNAME,encodedurl;
private List<String> playlistarray;
private List<MediaPlayer> mplayerList;
private ImageButton buttonPlay;
private List<S3ObjectSummary> playlist=null;
private ImageButton buttonStopPlay;
ProgressDialog progress;
URL url,currentsongurl;
private MediaPlayer player;
private AmazonS3Client mClient;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
playlistarray=new ArrayList<String>();
mplayerList=new ArrayList<MediaPlayer>();
if(isNetworkAvailable()) {
mClient = Util.getS3Client(MainActivity2.this);
initializeUIElements();
//new RefreshTask().execute();
buttonStopPlay.setVisibility(View.INVISIBLE);
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle(getResources().getString(R.string.app_name))
.setMessage(
getResources().getString(
R.string.internet_error))
.setPositiveButton("OK", null).show();
buttonStopPlay.setVisibility(View.INVISIBLE);
buttonPlay.setVisibility(View.INVISIBLE);
}
}
private void initializeUIElements() {
buttonPlay = (ImageButton) findViewById(R.id.Play);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (ImageButton) findViewById(R.id.Stop);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
finish();
startActivity(new Intent(MainActivity2.this, MainActivity2.class));
}
}
private void startPlaying() {
buttonPlay.setVisibility(View.INVISIBLE);
buttonStopPlay.setVisibility(View.VISIBLE);
progress = new ProgressDialog(this);
progress.setTitle("Message");
progress.setMessage("Loading Song ...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progress.dismiss();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
try {
// player.setNextMediaPlayer(mplayerList.get(2));
stopPlaying();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
});
}
private void stopPlaying() {
killMediaPlayer();
initializeMediaPlayer(playlistarray);
buttonPlay.setVisibility(View.VISIBLE);
buttonStopPlay.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer(List<String> playlist) {
player = new MediaPlayer();
int noOfSongs=playlist.size();
String url = "https://aryaradio.s3.amazonaws.com/us-east-1:eb604ac1-c4e3-4226-bea8-22f214a6b0b0/RecordingArya-9459.mp3.null";
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(url);
player.setOnPreparedListener(this);
player.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
});
} 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);
}
});
}
}
I'm facing with a problem. I want to get duration of video when i 'm recording it.
I can get duration of video when it's finish by code
MediaPlayer mp = MediaPlayer.create(mContext, Uri.parse(video));
if(mp == null)
return -1;
int duration = mp.getDuration();
mp.release();
But i want to get duration everytime when i record video to update to progressbar.
Hope your reply!
private class PlaybackObserver extends Thread {
public void run() {
currentPosition = 0;
try {
while (!killObserverThread) {
Thread.sleep(1000);
currentPosition = (int) mediaPlayer.getCurrentPosition();
runOnUiThread(new Runnable() {
public void run() {
yourProgressBar.setProgress(currentPosition);
}
});
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
killObserverThread = false;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (task == null || !task.isAlive()) {
task = new PlaybackObserver();
task.start();
}
startPlaying();
}
add a private class for your UiThread to update your seekbar/progressbar. Then start it from onResume()
I want to record audio from bluetooth headset. I search this and i find sources in this site about that. For example; How to record sound using bluetooth headset
Android MediaRecorder to AudioTrack, Recording and Playback
Text-To-Speech over bluetooth
public class MainActivity extends Activity {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private String outputFile = null;
private Button startBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private TextView text;
private AudioManager amanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
amanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
text = (TextView) findViewById(R.id.text1);
// store it to sd card
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/javacodegeeksRecording.3gpp";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stop(v);
}
});
playBtn = (Button)findViewById(R.id.play);
playBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
play(v);
}
});
stopPlayBtn = (Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopPlay(v);
}
});
}
public void start(View view){
try {
amanager.setMode(AudioManager.MODE_IN_CALL);
amanager.startBluetoothSco();
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text.setText("Recording Point: Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But program use in-built microphone. How can i use bluetooth headset audio?
Thanks.
As per android reference AudioManager.startBluetoothSco() start audio connection using startBluetoothSco() and stop android device speaker by using setSpeakerphoneOn(false). First connect your phone to device through bluetooth. Here is example for that.
Add permission "android.permission.MODIFY_AUDIO_SETTINGS" in manifest file.
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
System.out.println("ANDROID Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
/*
* Now the connection has been established to the bluetooth device.
* Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
* new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
*
* After finishing, don't forget to unregister this receiver and
* to stop the bluetooth connection with am.stopBluetoothSco();
*/
}
}
};
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
// Start Bluetooth SCO.
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothScoReceiver);
// Stop Bluetooth SCO.
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
}
Now start, stop and play audio based on requirement.
buttonStartRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Check audio permission
if (checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "AudioRecording.3gp";
// Start Media recorder
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStartRecording.setEnabled(false);
buttonStopRecording.setEnabled(true);
Toast.makeText(MainActivityOne.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
// Stop Media recorder
mediaRecorder.stop();
Toast.makeText(MainActivityOne.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
int selectedId = mRadioGroup.getCheckedRadioButtonId();
if (selectedId == R.id.radioButton) {
isAudioPlayInSameDevice = true;
} else {
isAudioPlayInSameDevice = false;
}
// if you want to play audio on your Mobile speaker then set isAudioPlayInSameDevice true
// and if you want to play audio to connected device then set isAudioPlayInSameDevice false.
if (isAudioPlayInSameDevice) {
audioManager.setMode(audioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(audioManager.MODE_NORMAL);
}
audioManager.setBluetoothScoOn(false);
audioManager.stopBluetoothSco();
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
// Start media player
System.out.println("Recorded Audio Path-" + AudioSavePathInDevice);
mediaPlayer.setDataSource(AudioSavePathInDevice);
if (isAudioPlayInSameDevice) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivityOne.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if (mediaPlayer != null) {
// Stop Media Player
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});
public void MediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
Click here to get the full source code.
To record from bluetooth you have to change the default phone Mic to headset Mic when recording starts this can be done by BluetoothSCO().
private static void startBluetoothRecording(
final OnBluetoothRecording BluetoothRecording,
final boolean resume, Context context) {
// TODO Auto-generated method stub
final int MAX_ATTEPTS_TO_CONNECT = 3;
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
final CountDownTimer timer = getTimer(BluetoothRecording, audioManager,
resume);
context.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(
AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
// cancel Timer
timer.cancel();
context.unregisterReceiver(this);
// pass through and true because
// recording from bluetooth so set 8000kHz
BluetoothRecording.onStartRecording(resume, true);
} else if (AudioManager.SCO_AUDIO_STATE_DISCONNECTED == state) {
if (count > MAX_ATTEPTS_TO_CONNECT) {
context.unregisterReceiver(this);
// Stop BluetoothSCO
audioManager.stopBluetoothSco();
// reset Counter
count = 0;
// stop timer
timer.cancel();
// false because still recording not started
BluetoothRecording.onStartRecording(resume, false);
} else {
// Increment Disconnect state Count
count++;
}
}
}
}, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));
// Start the timer
timer.start();
audioManager.startBluetoothSco();
}
For full class goto this link
I am developing one application where i want to play live stream radio. I have an url using which i will stream the radio and play. I have a play button by clicking which i want to play the radio. For that, i have written some code which is not at all working. Here is my code:
mp = new MediaPlayer();
try {
mp.setOnPreparedListener(this);
Log.d("Testing", "start111");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
String url="xxxxxx";
mp.setDataSource(url);
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.d("Testing", "Exception ::: 1111 "+e.getMessage());
} catch (IllegalStateException e) {
Log.d("Testing", "Exception ::: 2222 "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d("Testing", "IOException ::: 3333 "+e.getMessage());
e.printStackTrace();
}
Can anyone please help me??
You can find good information regarding radio streaming.
Github radio streaming example
and also there is a question in SOF which can also be helpful
Stackoverflow radio streaming example
Hope it will help. thanks
Try this.
public class RadioStream extends Activity {
private final static String stream = "http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p";
Button play;
MediaPlayer mediaPlayer;
boolean started = false;
boolean prepared = false;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_stream);
play = (Button) findViewById(R.id.play);
play.setEnabled(false);
play.setText("Loading..");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started) {
mediaPlayer.pause();
started = false;
play.setText("Play");
} else {
mediaPlayer.start();
started = true;
play.setText("Pause");
}
}
});
new PlayTask().execute(stream);
}
#Override
protected void onPause() {
super.onPause();
/* if(started)
mediaPlayer.pause();*/
}
#Override
protected void onResume() {
super.onResume();
/*if(started)
mediaPlayer.start();*/
}
#Override
protected void onDestroy() {
super.onDestroy();
// mediaPlayer.release();
}
private class PlayTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
play.setEnabled(true);
play.setText("Play");
}
}
}
Please do try the code below and call the given method at the on create of your activity or at the onclick listener of your button. Remember to handle the stop and start button the imgV is an imageView for my button.
private MediaPlayer player;
private void startMediaPlayer() {
String url = "http:yoururl.com"; // your URL here
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(isPlaying){
try {
mediaPlayer.prepareAsync();
progress.setVisibility(View.VISIBLE);
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
}
boolean isPlaying = true;
private void startPlaying() {
isPlaying = true;
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
imgV.setImageResource(R.drawable.stop);
}
private void stopPlaying() {
if (mediaPlayer.isPlaying()) {
isPlaying = false;
mediaPlayer.stop();
mediaPlayer.release();
initializeMediaPlayer();
}
imgV.setImageResource(R.drawable.play);
}
I am trying to make a service that plays in background which is unbounded. I have walked myself through some of the example codes on the internet but I can't get my application to play the radio when I'm calling the service class.
Please have a look at the code and tell me where I am going wrong... When I call MyService class from ArmanFMRadio onClick It toasts "My Service Created" & "My Service Started" but doesnt get to play the audio for the radio stream link. I've checked it otherwise and the link seems fine, so problem lies somewhere in the code to my understanding:
package com.etc.etcc;
public class ArmanFMRadio extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.armanfm);
initializeUIElements();
//initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setVisibility(View.VISIBLE);
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonPlay:
playSeekBar.setVisibility(View.VISIBLE);
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
startService(new Intent(this, MyService.class));
//startPlaying();
break;
case R.id.buttonStopPlay:
stopPlaying();
break;
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Just look at onClick on the above code, because this class works fine to my thinking.
MyService class:
package com.etc.etcc;
public class MyService extends Service {
private static final String TAG = "MyService";
private MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
onStart is deprecated method. you should use onStartCommand method.
Debug your code and check weather there is any Exception or something
Also you are using the service so possible that you service will call twice in that case your onStartCommand method will be called twice so there you will have to check the startId which you will get as a parameter. If startId > 1 that means previously your service is started so you can stop media player and again start a media player with latest source or you can just ignore the second request.
If you are not confidence with service you can put your code in the activity and check weather your code is working fine or not after that you can replace this code in the service.