How to Controll Player From different fragments on android - android

Please, I need my streaming audio player to be controlled from two different fragments:
Radiofragment and AboutFragment.
and here's my radio fragment
public class RadioFragment extends Fragment implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener{
AudioManager am;
ImageButton btnPlay = null;
private boolean isPlaying;
private PlayerManager playerManager;
private View view;
public RadioFragment(boolean p, PlayerManager pmanager){
this.isPlaying = p;
this.playerManager = pmanager;
}
#Override
public View onCreateView(LayoutInflater l, ViewGroup container, Bundle onSavedInstance){
super.onCreateView(l, container, onSavedInstance);
view = l.inflate(R.layout.activity_radio, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
btnPlay = (ImageButton)view.findViewById(R.id.btnPlay);
addButtonListeners();
}
private void addButtonListeners()
{
btnPlay.setAlpha(155);
btnPlay.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
onClickBtnPlay(v);
}
});
}
protected void onClickBtnPlay(View v)
{
if (isPlaying){
playerManager.pause();
isPlaying = false;
}
else{
if (playerManager == null){
playerManager = new PlayerManager(getString(R.string.link_streaming_radio), RadioFragment.this);
}
playerManager.play();
isPlaying = true;
}
}
#Override
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(MainActivity.TAG, sb.toString());
return true;
}
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp)
{
mp.stop();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
Log.d(MainActivity.TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}
in my AboutFragment, I have a layout with a play/pause button and
protected void onClickBtnPlay(View v)
{
if (isPlaying){
playerManager.pause();
isPlaying = false;
}
else{
if (playerManager == null){
playerManager = new PlayerManager(getString(R.string.link_streaming_radio), AboutFragment.this);
}
playerManager.play();
isPlaying = true;
}
}
here is the class where I controll the player:
public class PlayerManager{
private String xmlUrl;
private String server;
private MediaPlayer mp;
public PlayerManager(Fragment owner)
{
this.owner = owner;
this.server = "";
}
public void play()
{
server = path_to_server;
playMusic();
}
public void pause()
{
mp.stop();
mp.reset();
}
private void playMusic()
{
Uri myUri = Uri.parse(this.server);
try
{
if (mp == null){
this.mp = new MediaPlayer();
}
else{
mp.stop();
mp.reset();
}
mp.setDataSource(owner.getActivity(), myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener((OnPreparedListener) this.owner);
mp.setOnBufferingUpdateListener((OnBufferingUpdateListener) this.owner);
mp.setOnErrorListener((OnErrorListener) this.owner);
mp.setVolume(100,100);
mp.prepareAsync();
Log.d(MainActivity.TAG, "Done");
}
catch (Throwable t)
{
Log.d(MainActivity.TAG, t.toString());
}
}
}
can it be done with this kind of implementation or I have to use another approach?
Because I tried to pass playerManager via constructor but it seems to be in other activity context
so i get class cast exceptions. I also tried to pass Radiofragment context and got some null pointer exceptions
both from this last catch block above.
I need some light here, please..
thank you in advance!

You should have a foreground Service, containing the PlayerManager. You will then send play/pause commands from any activity or fragment you want.

Related

Playing media player inside fragment with background service

I'm trying to implement live stream radio by using fragment and background service, however every time I click to radio button on navigation drawer I couldn't reach the player because it generates one more and I can only control the second one. Here is my fragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_radio, container, false);
init(v);
ApiManager.getInstance().getRadioBroadcast(new ApiResponseLive.GetLiveBroadcastListener() {
#Override
public void onSuccess(StreamModel days) {
turnRadioOn(ApiManager.streamModel);
}
#Override
public void onFailure(String responseString) {
}
});
registerHandler(v);
return v;
}
private void turnRadioOn(StreamModel streamModel) {
HashMap<Integer, ArrayList<GenericStreamItem>> broadcastDays = new HashMap<>();
streamModel.setStreamAllArrays(broadcastDays);
BroadcastPagerAdapter radioPagerAdapter = new BroadcastPagerAdapter(getChildFragmentManager(), getContext(), TAG);
radioPager.setAdapter(radioPagerAdapter);
}
private void init(View v) {
radioPager = (ViewPager) v.findViewById(R.id.broadcastRadioPager);
radioTabLayout = (TabLayout) v.findViewById(R.id.tabsDays);
radioTabLayout.setupWithViewPager(radioPager);
radioPlay = (ToggleButton) v.findViewById(R.id.playButton);
radioScrollView = (ScrollView) v.findViewById(R.id.radioScroll);
}
private void start(String url) {
try {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setDataSource(url);
mp.prepareAsync();
mp.setOnCompletionListener(this);
Log.e("Radio::", "Working");
} catch (Exception e) {
Log.e("StreamAudioDemo", e.getMessage());
e.printStackTrace();
}
}
private void stop() {
try {
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void stopRadio() {
try {
Log.e("stopRadio::", "Pause");
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
}
private void registerHandler(View v) {
radioPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.e("Toggle::", "Enabled");
radioService = new RadioService();
radioService.initMediaPlayer(ApiManager.RADIO_URL);
} else {
Log.e("Toggle::", "Disabled");
stop();
stopRadio();
radioService.onDestroy();
}
}
});
v.findViewById(R.id.radioBroadcast).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public class RadioService extends Service implements MediaPlayer.OnErrorListener {
public void initMediaPlayer(String url) {
// ...initialize the MediaPlayer here...
ApiManager.getInstance().getRadioURL(new ApiResponseLive.GetTVStreamUrlListener() {
#Override
public void onSuccess(String tvUrl) {
start(ApiManager.RADIO_URL);
mp.setOnErrorListener(RadioService.this);
}
#Override
public void onFailure(String responseString) {
}
});
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
mp.reset();
return false;
}
#Override
public void onDestroy() {
if (mp != null) mp.release();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
}
Here is how I call fragment:
RadioFragment radioFragment = new RadioFragment();
fragment = fm.findFragmentByTag("radio");
radioDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fragment == null) {
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.activity_content))
.add(R.id.activity_content, radioFragment,
"radio").addToBackStack("main").commit();
} else {
fm.beginTransaction().replace(R.id.activity_content,
radioFragment, "radio");
}
fullView.closeDrawers();
}
});

Android media player won't start

I have created android application to stream online radio stations but when I click start button to play radio it won't start.In service I read ip address of file from url and add it to string.When user selects radio station I add port to string with ip address.Problem starts in mediaPlayer.setOnPreparedListener !!!
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL;
final String textSource = "http://audiophileradio.stream/Ip.txt";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new MyTask().execute();
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
#Override
public boolean onUnbind(Intent intent)
{
return super.onUnbind(intent);
}
private class MyTask extends AsyncTask<Void, Void, String>
{
String textResult;
#Override
protected String doInBackground(Void... params) {
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader
= new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textResult = stringText;
return textResult;
} catch (MalformedURLException e) {
e.printStackTrace();
textResult = e.toString();
} catch (IOException e) {
e.printStackTrace();
textResult = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("DebugTag", "Value: " + textResult);
super.onPostExecute(result);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(BackgroundService.this);
String radio = sharedPreferences.getString("station", "8000");
if (radio != null)
{
STREAM_URL += ":" + radio;
}
mediaPlayer = new MediaPlayer();
if (!mediaPlayer.isPlaying())
{
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
mediaPlayer.setOnCompletionListener(BackgroundService.this);
}
}
}
public class Main extends Fragment
{
private ImageButton buttonPlay;
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_main,container,false);
buttonPlay = (ImageButton) view.findViewById(R.id.buttonPlay);
mPlayer = new MediaPlayer();
initControls();
buttonPlay.setTag(1);
buttonPlay.setImageResource(R.drawable.play);
buttonPlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (Integer.parseInt(buttonPlay.getTag().toString()) == 1)
{
buttonPlay.setImageResource(R.drawable.stop);
view.setTag(0);
getActivity().startService(playbackServiceIntent);
Log.e("Play", "onStop");
Toast.makeText(getActivity(), "Play", Toast.LENGTH_SHORT).show();
} else
{
buttonPlay.setImageResource(R.drawable.play);
view.setTag(1);
mPlayer.stop();
getActivity().stopService(playbackServiceIntent);
Log.e("Stop", "onPlay");
Toast.makeText(getActivity(), "Stop", Toast.LENGTH_SHORT).show();
}
}
});
playbackServiceIntent = new Intent(getActivity(), BackgroundService.class);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Audiophileradio");
}
private void startService()
{
getActivity().startService(new Intent(getActivity(),BackgroundService.class));
}
private void stopService()
{
getActivity().stopService(new Intent(getActivity(),BackgroundService.class));
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar) view.findViewById(R.id.seekBar);
audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
//volumeSeekbar.setMax(100);
volumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
//volume.setText("Volume : " + progress + "%");
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
prepareAsynch should be called after setOnPreparedListener, otherwise it may happen that prepareAsynch finished working before the listener is assigned.
I have fixed the problem! Radio didn't work because I forgot to add http:// in ip address after reading it from url !!!

Media Player Fragement Crashes

You may have seen that I have had a problem with creating a Media Player a few months back. Well I am trying to get to the next stage by getting it to work in a fragment but the app keeps on stopping/crashing on me. Can someone help me please? Here is my activity/fragment (code-behind) class
public class MediaPlayerNew extends Fragment implements
android.media.MediaPlayer.OnCompletionListener,
android.media.MediaPlayer.OnPreparedListener,
android.media.MediaPlayer.OnErrorListener,
android.media.MediaPlayer.OnBufferingUpdateListener{
private MediaPlayer mp = null;
private String TAG = getClass().getSimpleName();
private Button play;
private Button pause;
private Button stop;
private TextView txtVStatus;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_player, container, false);
return view;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
play = (Button) getActivity().findViewById(R.id.btnPlay);
pause = (Button) getActivity().findViewById(R.id.btnPause);
stop = (Button) getActivity().findViewById(R.id.btnStop);
//status = (TextView) findViewById(R.id.txtVStatus);
pause.setEnabled(false);
stop.setEnabled(false);
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() {
//HTTP to BCRFM STREAM
Uri myUri = Uri.parse("http://37.187.193.36:8002");
try {
if (mp == null) {
this.mp = new android.media.MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(myUri.toString()); // 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(android.media.MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
final TextView textViewToChange = (TextView) getActivity().findViewById(R.id.txtVStatus);
textViewToChange.setText("Welcome to BCRfm");
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
}
private void pause() {
mp.pause();
final TextView textViewToChange = (TextView) getActivity().findViewById(R.id.txtVStatus);
textViewToChange.setText("You have paused your feed to BCRfm");
play.setEnabled(true);
pause.setEnabled(false);
stop.setEnabled(true);
}
private void stop() {
mp.stop();
final TextView textViewToChange = (TextView) getActivity().findViewById(R.id.txtVStatus);
textViewToChange.setText(" ");
play.setEnabled(true);
pause.setEnabled(false);
stop.setEnabled(false);
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(android.media.MediaPlayer mp) {
stop();
}
public boolean onError(android.media.MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case android.media.MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case android.media.MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case android.media.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(android.media.MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}
There are issues with your code, and I will number them for clarity.
1) With methods onCreateView and onCreate, at least (check others!), place the keyword #Override above the methods declaration. Please compare sample codes in Google.
Failure to do this and perhaps the compiler would not consider it as overriding.
2) There is nothing wrong with
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
This is normal code.
3) Change from:
#Override
public void onDestroy() {
super.onDestroy();
}
TO:
#Override
public void onDestroy() {
stop();
super.onDestroy();
}
The main difference is calling stop() before onDestroy() call. When you're destructing, it's standard to call destroy/destruct after all the other codes.
And...you should stop the Media Player, otherwise it will still keep playing whatever even after the app exits.
Its okay, I fixed it.
I changed:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);......
to
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);..
And it works perfectly, only thing is when I want to switch from this fragment to another, the app crashes. Any tips?
Fixed it
Changed
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
to
#Override
public void onDestroy() {
super.onDestroy();
}

Audio Streaming Seekbar Hides while song is playing

I can't find a way to stop hiding the seekbar. As soon as the song plays the seekbar hides after 2-3 sec. I am really new into this so not really sure how I can approach to this issue. I tried putting mediaController.show() into my methods when the song is playing but no luck. I found this code from a Youtube Channel below is the code:
public class MainActivity extends ListActivity implements OnPreparedListener,
MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private ListView list;
private MainArrayAdapter adapter;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = getListView();
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
ArrayList<String> array_list_music = new ArrayList<String>();
array_list_music.add("Sammy Kaye And His Orchestra" + " ### "
+ "Minka (1941)" + " ### "
+ "http://incoming.jazz-on-line.com/a/mp3w/1941_149.mp3");
adapter = new MainArrayAdapter(MainActivity.this, array_list_music);
setListAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Object item = getListView().getItemAtPosition(arg2);
String the_list_item = item.toString();
Toast.makeText(MainActivity.this,
"You clicked " + the_list_item, Toast.LENGTH_LONG)
.show();
String[] aux = the_list_item.split(" ### ");
String url_to_play = aux[2];
playAudio(url_to_play);
}
});
}
private void playAudio(String url_to_play) {
//----- stop & reset
try {
mediaPlayer.stop();
mediaPlayer.reset();
} catch (Exception e) {
// TODO: handle exception
}
try {
mediaPlayer.setDataSource(url_to_play);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
Log.e(TAG, "Could not open file " + url_to_play + " for playback.",
e);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return true;
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public void seekTo(int arg0) {
mediaPlayer.seekTo(arg0);
}
#Override
public void start() {
mediaPlayer.start();
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(list);
mediaController.show();
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
}

Shoutcast streaming not working in android device 2.2

I am doing shoutcast streaming in my app. The app was playing the link on android emulator 2.2 but the same was not playing in device. Why? I am using galaxy tab 2.2. Any settings required to be done? Help is appreciated. Is there any special permission required in manifest?
public class radiog 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://stream.radiosai.net:8020/");
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 + "%");
}
}

Categories

Resources