MediaController doesn't seem to show up - android

I have an android app with a detail activity, that detail activity has few tabs with underlying fragments. One of these fragments is plain list with a name of audio files when I click each line I'm playing the clicked audio files.
Everything works OK, but I would like to have some means of seeing a progress of the playback and ability to stop a playback, I was trying to add MediaController but even though I'm creating it without errors no media control is visible on a screen.
I'm not sure if I'm doing it in a correct way any help you would be appreciated.
Thanks a lot,
Radek
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.audio_row,parent,false);
}
TextView textView = (TextView) convertView.findViewById(R.id.rowText);
textView.setText("" + jsonAudio.getJSONObject(position).getString("description"));
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String audioFileName = jsonAudio.getJSONObject(position).getString("file");
Toast.makeText(context, "audio item clicked: " + audioFileName, Toast.LENGTH_SHORT).show();
AssetFileDescriptor descriptor = context.getAssets().openFd(audioFileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
MediaPlayer mediaPlayer=new MediaPlayer();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), start, end);
mediaPlayer.prepare();
// not doing really anything
MediaController mediaController = new MediaController(context);
mediaController.setAnchorView(v);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});

Please check the below code for your refrence
In your code you have passed the TextView in the mediaController need to pass the SurfaceView instead of TextView and you need to set the MediaPlayer in the MediaController
JAVA file.
import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.util.Log;
import android.media.MediaPlayer.OnPreparedListener; import android.view.MotionEvent; import android.widget.MediaController; import android.widget.TextView;
import java.io.IOException;
public class AudioPlayer extends Activity implements OnPreparedListener, MediaController.MediaPlayerControl{ private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private MediaPlayer mediaPlayer; private MediaController mediaController; private String audioFile;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.audio_player);
audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);
((TextView)findViewById(R.id.now_playing_text)).setText(audioFile);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}
}
#Override protected void onStop() { super.onStop(); mediaController.hide(); mediaPlayer.stop(); mediaPlayer.release(); }
#Override public boolean onTouchEvent(MotionEvent event) { //the MediaController will hide after 3 seconds - tap the screen to make it appear again mediaController.show(); return false; }
//--MediaPlayerControl methods---------------------------------------------------- public void start() { mediaPlayer.start(); }
public void pause() { mediaPlayer.pause(); }
public int getDuration() { return mediaPlayer.getDuration(); }
public int getCurrentPosition() { return mediaPlayer.getCurrentPosition(); }
public void seekTo(int i) { mediaPlayer.seekTo(i); }
public boolean isPlaying() { return mediaPlayer.isPlaying(); }
public int getBufferPercentage() { return 0; }
public boolean canPause() { return true; }
public boolean canSeekBackward() { return true; }
public boolean canSeekForward() { return true; } //--------------------------------------------------------------------------------
public void onPrepared(MediaPlayer mediaPlayer) { Log.d(TAG, "onPrepared"); mediaController.setMediaPlayer(this); mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
} }
XML file-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_audio_view" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_gravity="center"
android:orientation="vertical"> <TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center" android:text="Now playing:"
android:textSize="25sp" android:textStyle="bold" /> <TextView
android:id="#+id/now_playing_text" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginTop="20dip"
android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
android:layout_gravity="center" android:text="Now playing.."
android:textSize="16sp" android:textStyle="italic" /> </LinearLayout>

I had to tweak Patrick's solution a bit to play the file from assets folder but it worked great, here is reformatted java file for easy cut and paste if anyone needs it.
import android.content.res.AssetFileDescriptor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.MotionEvent;
import android.widget.MediaController;
import android.widget.TextView;
import java.io.IOException;
public class MediaPlayer extends AppCompatActivity implements OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private android.media.MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFileName = "item1_audio1.mp3";;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_audio_view);
((TextView) findViewById(R.id.now_playing_text)).setText(audioFileName);
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
AssetFileDescriptor descriptor = MediaPlayer.this.getAssets().openFd(audioFileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), start, end);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFileName + " for playback.", e);
}
}
#Override
public void onPrepared(android.media.MediaPlayer mp) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
}
#Override
public boolean onTouchEvent(MotionEvent event) { //the MediaController will hide after 3 seconds - tap the screen to make it appear again
mediaController.show();
return false;
}
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public void onStart() {
super.onStart();
}
}

Related

Android MediaPlayer seekTo() function working incorrect

I have a problem when using MediaPlayer to play video from url.
The follow of program : create an activity to play video -> press Home button -> back to app.
The requirement is video play from start, when press Home button video continuos play(only audio), and when back to app, video must play continuous(combine movie and audio).
The first, I created a MediaPlayer variable to play video. When Home button is pressed, MediaPlayer play continuous. But when back to app, video cannot displayed(black screen). So, I created other MediaPlayer variable to solved this issue. But when I using seekTo() function to seek second MediaPlayer to position of first MediaPlayer, this function is working incorrect.
import java.io.IOException;
import com.example.videotest.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlayVideoActivity extends Activity implements OnClickListener,SurfaceHolder.Callback, FGMediaController.MediaPlayerControl {
SurfaceView videoSurface,videoSurfaceFullscreen,videoSurfaceSmallsceen;
MediaPlayer player, backupPlayer;
FGMediaController controller;
LinearLayout llControllerBar;
public boolean isFullscreen = false;
int videoDuration;
int videoCurrent;
SurfaceHolder viewHolder = null;
boolean isPaused = false;
String videoUrl = "http://cdn-smatopi.tv-bank.com/movie/867/867-32/867-32-2015042306-D3/hls/hls3/867-32-2015042306-D3-HLS3.m3u8";
Button btnSeek, btnRelease;
int currentPos = 30000;
boolean videoPrepared = false;
boolean backupPrepared = false;
boolean mVideoSizeIsSet = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.playvideo);
btnSeek = (Button) findViewById(R.id.btnSeek);
btnRelease = (Button) findViewById(R.id.btnRelease);
videoSurface = (SurfaceView)findViewById(getResources().getIdentifier("vvVideo", "id", getPackageName()));
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
backupPlayer = new MediaPlayer();
controller = new FGMediaController(this);
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(videoUrl));
player.prepareAsync();
//backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//backupPlayer.setDataSource(this, Uri.parse(videoUrl));
//backupPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
btnSeek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("Huhu",currentPos + "");
backupPlayer.seekTo(currentPos);
}
});
btnRelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
backupPlayer.stop();
backupPlayer.release();
}
});
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(PlayVideoActivity.this);
controller.setAnchorView((FrameLayout) findViewById(PlayVideoActivity.this.getResources().getIdentifier("videoSurfaceContainer", "id", PlayVideoActivity.this.getPackageName())));
player.start();
}
});
}
#Override
public void onDestroy(){
//backupPlayer.release();
player.release();
super.onDestroy();
}
#Override
public void onResume(){
Log.e("Surface Created","OnResume");
super.onResume();
}
// Implement SurfaceHolder.Callback
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e("Surface Created","Surface Created! " + holder);
if(viewHolder != null){
viewHolder = holder;
backupPlayer = new MediaPlayer();
try {
backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
backupPlayer.setDataSource(this, Uri.parse(videoUrl));
backupPlayer.prepareAsync();
backupPlayer.setDisplay(holder);
backupPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
backupPrepared = true;
backupPlayer.start();
}
});
backupPlayer.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
if (width == 0 || height == 0){
Toast.makeText(getApplicationContext(),"Width = 0 Height = 0"+ mp.getDuration(), Toast.LENGTH_LONG).show();
}else{
if(backupPrepared){
backupPrepared = false;
currentPos = player.getCurrentPosition();
player.reset();
Toast.makeText(getApplicationContext(),"Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos, Toast.LENGTH_LONG).show();
Log.e("Huhu","Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos);
backupPlayer.seekTo(currentPos); // If you set currentPos = 20000ms or 30000ms backupPlayer can to seek, but if you set currentPos = 10000ms backupPlayer cannot seek !
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
player.setDisplay(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e("Surface Created","surfaceDestroyed! " + player.getCurrentPosition());
viewHolder = holder;
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
//Log.printLog(Log.ERROR, "CURRENT :"+player.getCurrentPosition());
int current = 0;
try{
current = player.getCurrentPosition();
}catch(Exception e){
e.printStackTrace();
}
return current;
}
#Override
public int getDuration() {
int duration = 0;
try{
duration = player.getDuration();
}catch(Exception e){
e.printStackTrace();
}
return duration;
}
#Override
public boolean isPlaying() {
boolean isPlaying = false;
try{
isPlaying = player.isPlaying();
}catch(Exception e){
e.printStackTrace();
}
return isPlaying;
}
#Override
public void pause() {
player.pause();
}
#Override
public void seekTo(int i) {
player.seekTo(i);
}
#Override
public void start() {
player.start();
}
#Override
public boolean isFullScreen() {
return isFullscreen;
}
#Override
public void toggleFullScreen() {
// TODO Auto-generated method stub
}
#Override
public void doBackPressed() {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
}
}

android mediaplayer double play

I have a problem. This is stream player it is playing fine but when I start play, change app and again start player app the stop button is disabled.
If I pressing play again - it start plaing double music and I cannot stop first stream playing.
In short: I need one app and one sound and possibility to stop sound (without double playing)
import com.erkutaras.media.audio.url.R;
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.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://play.org.ua:8000/";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}
In your OnClick() method add if:
if (mediaPlayer.isPlaying())
{
//mediaPlayer.pause; //or what you want instead double play
}
else
{
//your code
}

Cannot play a mp3 file from a url with htts protocol in android

I am play a mp3 file from url containing a https protocol extention , I get a mediaplayer failed to prepare exception but when i use a http protocol the code runs fine
/**
import com.erkutaras.media.audio.url.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
// private final String URL = "http://android.erkutaras.com/media/audio.mp3";
private final String URL = "https://icanbeanything.com/en/Fearless/afraid-of-change.mp3";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}
/////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
*/
If you developing on before Android 3.1
HTTPS is not supported before Android 3.1.
See this link
Android Supported Media Formats

MediaPlayer android doesnt play

i use these lines to play some audio file with mediaplayer, both on a service and in an activity, yet there is no sound on my device, what could be the reason? and what should i try to do to understand whats wrong and finally fix that?
MediaPlayer mp = MediaPlayer.create(this, R.raw.alert);
mp.start();
Intent viewMediaIntent = new Intent();
viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(objectFilePath);
viewMediaIntent.setDataAndType(Uri.fromFile(file), "audio/*");
viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(viewMediaIntent);
http://developer.android.com/reference/android/media/MediaPlayer.html
Check out the state diagram in the MediaPlayer docs.
After you've created the MediaPlayer it is in the Idle state. As you can see, you need to initialize and prepare it before you call start().
Check the following code, it works fine for me. I hope it will work for you also.....Dont forget to add Audio PlayBack permission in android Manifest File
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.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://android.erkutaras.com/media/audio.mp3";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}

Android app gets slow when I change audio streaming stations

I hope someone can help me with this.
Here's y problem: I have an icecast server with a couple of channels. I developed an app to listen those stations but when I change from one station to another one the app gets really slow.
Here's the code to change the station:
public static void setAndPlay(MediaPlayer player, String source) {
player.reset();
try {
player.setDataSource(source);
player.prepare();
} catch (IOException e) {
//TODO: handle exception
}
}
And here's when the mediaPlayer starts:
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer player) {
player.start();
}
});
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class SimpleMusicStream extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp = null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("http://fr3.ah.fm:9000/");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Play"
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<Button
android:text="Pause"
android:id="#+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<Button
android:text="Stop"
android:id="#+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>

Categories

Resources