How to record bluetooth headset audio? - android

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

Related

how to listen to the radio stream instantly without waiting in Android?

I always use this method to read the flow of streaming radio stations.
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(play.getTag().equals("Start")){
notificationBar("Click To Stop Radio",nom);
play.setEnabled(false);
startPlaying(image, nom, urlradio);
}else{
play.setTag("Start");
stopPlaying(urlradio);
play.setImageResource(R.drawable.play);
}
}
});
OnAudioFocusChangeListener focusChangeListener =
new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
player.setVolume(0.2f, 0.2f);
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
player.pause();
break;
case (AudioManager.AUDIOFOCUS_LOSS) :
// player.stop();
break;
case (AudioManager.AUDIOFOCUS_GAIN) :
// Return the volume to normal and resume if paused.
player.setVolume(1f, 1f);
player.start();
break;
default: break;
}
}
};
// Request audio focus for playback
int result = audioManager.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so u can do u stuff now .
}
private void startPlaying(String image,String nom,String urlradio) {
initializeMediaPlayer(urlradio);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
playSeekBar.setVisibility(View.INVISIBLE);
play.setEnabled(true);
play.setImageResource(R.drawable.stop);
play.setTag("Stop");
}
});
}
private void stopPlaying(String urlradio) {
if (player != null) {
player.stop();
player.release();
player = null;
}
notificationClose(1);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer(String radio) {
player = new MediaPlayer();
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
try {
player.setDataSource(radio);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
But in some radio the stream I expected 20 to 30 seconds to be listen and I saw in some application that the flow passes instantaneous .
how to listen to the radio stream instantly without waiting?

Audio Capture Android doesn't work

My app needs to implement audio capture function .
i have followed several tutorials and google guides . so i have made the code below.
it works fine until the second attempt. when i capture my voice once, it 's able to reply what i have said.
in the second attempt, when i think it had to over write the file created, the app crashes. probably i ignore some methods.
could you help me ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inizializzaView();
Media();
SetListner();
}
public void inizializzaView(){
Text=(TextView)findViewById(R.id.textview);
Registra=(Button)findViewById(R.id.bottonereg);
Ascolta=(Button)findViewById(R.id.bottoneascolta);
Stop=(Button)findViewById(R.id.bottonestop);
Stop.setEnabled(false);
Ascolta.setEnabled(true);
}
public void SetListner(){
Registra.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start(v);
}
});
Stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stop(v);
}
});
Ascolta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play(v);
}
});
}
public void Media(){
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/recording.3gp";;
// android voice recorder
media = new MediaRecorder();
media.setAudioSource(MediaRecorder.AudioSource.MIC);
media.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
media.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
media.setOutputFile(outputFile);
}
public void start(View view){
try {
media.prepare();
media.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Registra.setEnabled(false);
Stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stai registrando Burlone !!!", Toast.LENGTH_LONG).show();
}
public void stop(View view){
media.stop();
media.release();
media = null;
Stop.setEnabled(false);
Registra.setEnabled(true);
Toast.makeText(getApplicationContext(), "Registrazione Terminata",
Toast.LENGTH_LONG).show();
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
myPlayer.release();
Ascolta.setEnabled(true);
Stop.setEnabled(false);
Toast.makeText(getApplicationContext(), "Ascolta.......",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i've solved !!!.
the code needs to be implemented .
public void start(View view){
try {
Media();// this creates a new object whenever you capture new voice.
media.prepare();
media.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Registra.setEnabled(false);
Stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stai registrando Burlone !!!", Toast.LENGTH_LONG).show();
}
public void stop(View view){
media.stop();
media.release();
media = null;
Stop.setEnabled(false);
Registra.setEnabled(true);
Toast.makeText(getApplicationContext(), "Registrazione Terminata",
Toast.LENGTH_LONG).show();
}

unable to stop Audio Recording,Thread not working properly and application stops unfortunately

I am making a sample program for recording audio.I have a button for starting and stopping the recording.I am running a thread so that i can record until 30 sec.My problem is when before reaching to 30sec ,if i click on stopButton ,my application stops unfortunately.Now i am not getting the problem.
Following is my code:
public class AudioRecordingActivity extends Activity {
private Button RecordButton;
boolean recording;
MediaRecorder recorder ;
Thread RecordThread;
Handler recordHandler;
private TextView timeText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timeText=(TextView)findViewById(R.id.textView1);
RecordButton=(Button)findViewById(R.id.btnRecord);
RecordButton.setText("Start Recording");
RecordButton.getBackground().setColorFilter(new LightingColorFilter(-16711936, 0));
recording=false;
RecordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (recording)
{
recording=false;
stopRecording();
RecordButton.setText("Start Recording");
RecordButton.getBackground().setColorFilter(new LightingColorFilter(-16711936, 0));
// Toast.makeText(getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
}//if(recording)
else if(!recording) {
recording=true;
startRecording();
RecordButton.setText("Stop Recording");
RecordButton.getBackground().setColorFilter(new LightingColorFilter(-65536, 0));
// Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
recordHandler = new Handler();
RecordThread=new Thread(new Runnable() {
int j;
#Override
public void run() {
// TODO Auto-generated method stub
for( j=30;j>=0;j--){
if(recording){
recordHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
setTimer(j);
}//handler run
});//post
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//catch
}else if (!recording)
{
stopRecording();
}
}//for
}//run
});
RecordThread.start();
}
}
});
}//onCreate
protected void startRecording() {
// TODO Auto-generated method stub
Random generator = new Random();
int n = 1000;
n = generator.nextInt(n);
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/AudioRecord");
if(!folder.exists())
{
folder.mkdirs();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/AudioRecord/audiorecord"+n+".3gp";
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFile(path);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
Toast.makeText(getApplicationContext(),"Saving Audio as"+ path,
Toast.LENGTH_LONG).show();
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "IllegalStateException called", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "prepare() failed", Toast.LENGTH_LONG).show();
}
recorder.start();
}
private void stopRecording() {
recorder.stop();
recorder.release();
recorder = null;
}
private void setTimer(int j) {
// TODO Auto-generated method stub
((TextView)findViewById(R.id.textView1)).setText(String.valueOf(j) + "sec");
if(j==0){
recording=false;
}
}
}//class end
Audio is been recorded perfectly.I guess the problem is with stopping the audio and thread.I don't know where the correction are to be made.
THanks for the help in advance.
Problem solved: Following corrections were made..
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (recording)
{
if(recorder!=null){
recorder.stop();
recorder.release();
recorder = null;
}
recording=false;
RecordButton.setText("Start Recording");
RecordButton.getBackground().setColorFilter(new LightingColorFilter(-16711936, 0));
// Toast.makeText(getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
}
...
private void setTimer(int j) {
// TODO Auto-generated method stub
timeText.setText(String.valueOf(j) + "sec");
if ((recording) && (j==1)){
recorder.stop();
recorder.release();
recorder = null;
recording=false;
RecordButton.setText("Start Recording");
RecordButton.getBackground().setColorFilter(new LightingColorFilter(-16711936, 0));
}
}

Android: Starting a service to play radio channels

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.

How to handle phone call while doing live audio streaming in android

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.

Categories

Resources