I have a ListView which lists audio recordings. When I click on one to play, it goes out the the internet and retrieves the audio and plays it. When it plays the scrolling locks up.
Once the MediaPlayerhas stopped I can scroll like normal. This isn't a thread issue because the MediaPlayer is playing on another thread.
This is the MediaPlayer AsyncTask:
private class PlayAudio extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
nowPlaying = true;
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if(isAdded()) {
stopAudio();
}
PvmUtils.longToast(context, getString(R.string.error_load_msg));
return false;
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
setButtonColors(2);
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopAudio();
sendPostMessageRead(new Callbacks.SendPostMessageReadCallback() {
#Override
public void sendPostMessageReadCallback(boolean gotMessageReadResponse) {
if (gotMessageReadResponse) {
MessageLog message = log.get(listPosition);
message.setMessageStatus("read");
if (message.isReply()) {
currentMetaTextView.setText("");
MyFcmListenerService.newMessages--;
ShortcutBadger.applyCount(context, MyFcmListenerService.newMessages);
}
} else {
Log.d(LOG_TAG, "sendPostMessageReadCallback returned false, error may have occurred");
}
}
});
}
});
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
//Uri uri = Uri.parse(Keys.getpvmURL() + "android/retrieveMessage?messageId=" + params[0]);
//player.setDataSource(params[0].replaceFirst("https","http"));
Uri uri = Uri.parse(params[0]);
Map<String, String> headers = new HashMap<>();
headers.put("authorisation", encryption.getID().toString());
player.setDataSource(context, uri, headers);
} catch (IOException e) {
e.printStackTrace();
stopAudio();
} try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
stopAudio();
}
player.start();
return null;
}
}
This is the clicklistener for the list item:
ListAdapter newAdapter = new ListAdapter(getActivity());
if (this.log == null) {
list.setAdapter(populateAdapter(newAdapter,new ArrayList<MessageLog>()));
} else {
list.setAdapter(populateAdapter(newAdapter,log));
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(LOG_TAG, Integer.toString(position));
if (log != null && position < log.size()) {
if (!nowPlaying && log.get(position).getUrl() != null) {
try {
stopAudio();
setButtonColors(0, currentPlaying);
// Show the play controls.
currentPlaying = position;
nowPlaying = true;
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
listPosition = position;
currentButton = view;
Log.d(LOG_TAG, log.get(position).getUrl());
/*
MessagePlaybackDialogFragment playFrag = MessagePlaybackDialogFragment.newInstance(log.get(listPosition),
new Callbacks.OnPlaybackFinishedListener() {
#Override
public void onPlaybackDone() {
// TODO set as not new
}
});
playFrag.show(getFragmentManager(), "playFrag");*/
// MessagePlaybackDialogFragment playFrag = MessagePlaybackDialogFragment.newInstance(log.get(listPosition));
// playFrag.show(getFragmentManager(), "playFrag");
currentMetaTextView = (TextView) view.findViewById(R.id.voiceMessageMetaText);
currentPlayPauseImageView = (ImageView) view.findViewById(R.id.voiceMessagePlayPauseImage);
currentMessageBackground = (RelativeLayout) view.findViewById(R.id.voiceMessageRectangleBackground);
setButtonColors(1);
currentAudio = new PlayAudio().execute(log.get(listPosition).getUrl());
} catch (Exception e) {
stopAudio();
e.printStackTrace();
}
} else if (position == listPosition){
stopAudio();
} else if (nowPlaying){
stopAudio();
currentPlaying = position;
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
listPosition = position;
currentButton = view;
Log.d(LOG_TAG, log.get(position).getUrl());
currentMetaTextView = (TextView) view.findViewById(R.id.voiceMessageMetaText);
currentPlayPauseImageView = (ImageView) view.findViewById(R.id.voiceMessagePlayPauseImage);
currentMessageBackground = (RelativeLayout) view.findViewById(R.id.voiceMessageRectangleBackground);
setButtonColors(0, currentPlaying);
setButtonColors(1);
currentAudio = new PlayAudio().execute(log.get(listPosition).getUrl());
}
}
}
});
Try prepareAsync instead, this is my code...
mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mp.setDataSource(a.getUrl());
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
activityList.get(position).setDuration(mp.getDuration()/1000);
holder.playButton.clearAnimation();
mp.start();
}
});
Related
I am fairly new to android development, so what I am trying to make is an app that can play audio from url,
I want to show progress bar while the audio file is loading from the web(some audio files are big over 15mb) How can I do that?
here is my audio play activity
public class AudioPlayerActivity extends AppCompatActivity {
String Content_id,audio_url;
AudioView audioView;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_player);
audio_url = getIntent().getStringExtra("audio_url");
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
audioView=(AudioView)findViewById(R.id.audioview);
//pDialog.setMessage("Please Wait...");
//showDialog();
try {
audioView.setDataSource(audio_url);
audioView.start();
} catch (IOException e) {
e.printStackTrace();
}
//hideDialog();
}
#SuppressLint("MissingSuperCall")
#Override
protected void onStop() {
super.onPause();
audioView.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
audioView.pause();
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
I am sharing the whole code for a well customized MediaPlayer. Just follow and implement this -
public class MusicActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {
private ImageView cross, settings;
private TextView titleText;
private RecyclerView recyclerView;
private ProgressBar mProgressBar;
private String id;
private String title;
private String audio;
private String english;
private String transliteration;
private String urdu;
private LinearLayoutManager linearLayoutManager;
private ProgressDialog progressDialog;
private float scrollTo;
private ImageView play_button;
private View view;
private TextView audiotitle;
private LinearLayout hide;
private ImageView play, rewind, forward;
private TextView currentTime, endTime;
private SeekBar seekbar;
private RelativeLayout progress_layout;
private LinearLayout offline_layout;
private ImageView download;
private ImageView cancel;
private Dialog mBottomSheetDialog;
private MediaPlayer mp;
private Handler mHandler = new Handler();
private Util util;
private boolean flag = false;
private ProgressBar progressBar;
Boolean isInternetPresent = false;
ConnectionDetector cd;
private String open_download_string;
private ProgressBar mProgress;
private ArrayList<String> filePath = new ArrayList<String>();
private int seekForwardTime = 10 * 1000;
private int seekBackwardTime = 10 * 1000;
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if (mp != null) {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
endTime.setText(util.milliSecondsToTimer(totalDuration) + " min");
// Displaying time completed playing
currentTime.setText(util.milliSecondsToTimer(currentDuration) + " min");
// Updating progress bar
int progress = (int) (util.getProgressPercentage(currentDuration, totalDuration));
seekbar.setProgress(progress);
mHandler.postDelayed(this, 100);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
mp = new MediaPlayer();
cross = (ImageView) findViewById(R.id.cross);
settings = (ImageView) findViewById(R.id.settings);
titleText = (TextView) findViewById(R.id.title);
play_button = (ImageView) findViewById(R.id.play_button);
setMusicPlayerWidgets();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString(Constant.SONG_TITLE);
audio = bundle.getString(Constant.SONG_AUDIO);
/*mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
play_button.setVisibility(View.VISIBLE);
if(mp.isPlaying()){
if(mp!=null){
play_button.setImageResource(R.drawable.pause);
}
}else{
play_button.setImageResource(R.drawable.play);
}
}
});*/
/* play_button.setVisibility(View.VISIBLE);
if(mp.isPlaying()){
if(mp!=null){
play_button.setImageResource(R.drawable.pause);
}
}else{
play_button.setImageResource(R.drawable.play);
}*/
} else {
progressBar.setVisibility(View.GONE);
play_button.setVisibility(View.GONE);
}
titleText.setText(title);
}
}
#Override
public void onResume() {
super.onResume();
setUpMusicPlayer();
}
/**
* MUSIC PLAYER IMPLEMENTATION
**/
private void setMusicPlayerWidgets() {
view = getLayoutInflater().inflate(R.layout.media_player_layout, null);
play = (ImageView) view.findViewById(R.id.play);
rewind = (ImageView) view.findViewById(R.id.rewind);
forward = (ImageView) view.findViewById(R.id.forward);
audiotitle = (TextView) view.findViewById(R.id.title);
hide = (LinearLayout) view.findViewById(R.id.hide);
seekbar = (SeekBar) view.findViewById(R.id.seekbar);
currentTime = (TextView) view.findViewById(R.id.time_current);
endTime = (TextView) view.findViewById(R.id.time_end);
progress_layout = (RelativeLayout) view.findViewById(R.id.progress_layout);
offline_layout = (LinearLayout) view.findViewById(R.id.offline_layout);
download = (ImageView) view.findViewById(R.id.download);
cancel = (ImageView) view.findViewById(R.id.cancel);
mBottomSheetDialog = new Dialog(DuaReadingsActivity.this, R.style.MaterialDialogSheet);
}
private void setUpMusicPlayer() {
audiotitle.setText(title);
seekbar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
play_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
File dirFiles = DuaReadingsActivity.this.getFilesDir();
for (String strFile : dirFiles.list()) {
filePath.add(strFile);
}
if (!filePath.contains(open_download_string)) {
cd = new ConnectionDetector(DuaReadingsActivity.this);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new DownloadFileFromURL().execute(audio);
} else {
cd.noInternetDialog();
}
}
mediaBottomSheet();
}
}
});
}
private void mediaBottomSheet() {
mBottomSheetDialog.setContentView(view);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.show();
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
if (mBottomSheetDialog.isShowing()) {
mBottomSheetDialog.dismiss();
}
}
};
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// handler.removeCallbacks(runnable);
}
});
handler.postDelayed(runnable, 10000);
hide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBottomSheetDialog.dismiss();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
}
}
});
rewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rewindSong();
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forwardSong();
}
});
}
public void rewindSong() {
if (mp != null) {
int currentPosition = mp.getCurrentPosition();
if (currentPosition - seekBackwardTime >= 0) {
mp.seekTo(currentPosition - seekBackwardTime);
} else {
mp.seekTo(0);
}
}
}
public void forwardSong() {
if (mp != null) {
int currentPosition = mp.getCurrentPosition();
if (currentPosition + seekForwardTime <= mp.getDuration()) {
mp.seekTo(currentPosition + seekForwardTime);
} else {
mp.seekTo(mp.getDuration());
}
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
if (mBottomSheetDialog.isShowing()) {
mBottomSheetDialog.dismiss();
}
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.seekTo(0);
flag = false;
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
}
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = util.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
public void playSong() {
try {
/*mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(audio);
mp.prepare();*/
mp.start();
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
seekbar.setProgress(0);
seekbar.setMax(100);
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} /*catch (IOException e) {
e.printStackTrace();
}*/
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
mp.reset();
mp.prepareAsync();
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
}
final Handler handler = new Handler();
new Runnable() {
public void run() {
finish();
handler.postDelayed(this, 150);
}
};
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
mp.reset();
mp.prepareAsync();
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
}
final Handler handler = new Handler();
new Runnable() {
public void run() {
finish();
handler.postDelayed(this, 150);
}
};
if((mProgress != null) && (mProgress.getProgress() != 0)){
File file = new File(DuaReadingsActivity.this.getFilesDir() + "/" +open_download_string);
file.delete();
if(file.exists()){
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
}
// finish();
}
#Override
protected void onPause() {
super.onPause();
if (mp.isPlaying()) {
mp.pause();
}
}
#Override
protected void onStop() {
super.onStop();
if (mp.isPlaying()) {
mp.pause();
}
}
private class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress_layout.setVisibility(View.VISIBLE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.GONE);
mProgress = (ProgressBar) view.findViewById(R.id.circularProgressbar);
mProgress.setProgress(0);
mProgress.setSecondaryProgress(100);
mProgress.setMax(100);
mProgress.setIndeterminate(false);
mProgress.setProgressDrawable(getResources().getDrawable(R.drawable.download_progress));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
FileOutputStream outputStream = openFileOutput(audio.substring(audio.lastIndexOf('/') + 1), Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
outputStream.write(data, 0, count);
}
outputStream.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
getFilesDir().getAbsolutePath();
progress_layout.setVisibility(View.GONE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.VISIBLE);
mProgress.setProgress(0);
}
#Override
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
progress_layout.setVisibility(View.GONE);
download.setVisibility(View.VISIBLE);
offline_layout.setVisibility(View.GONE);
mProgress.setProgress(0);
DownloadFileFromURL.this.cancel(true);
File file = new File(DuaReadingsActivity.this.getFilesDir() + "/" +open_download_string);
file.delete();
if(file.exists()){
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
}
});
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
progress_layout.setVisibility(View.VISIBLE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.GONE);
cd = new ConnectionDetector(DuaReadingsActivity.this);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new DownloadFileFromURL().execute(audio);
} else {
cd.noInternetDialog();
}
}
});
}
}
}
This will work perfectly if you follow well. Cheers!!
In my Android app videos are played with subtitles using videoview. The problem is when I'm pressing forward or dragging the seekbar subtitles are displaying, but when I'm pressing backward or dragging the seekbar backwards subtitles are not displaying. Below is the full code.
public class MainActivity extends AppCompatActivity implements View.OnTouchListener,MediaPlayer.OnInfoListener,MediaPlayer.OnSeekCompleteListener {
MediaController ctlr;
VideoView videoview;
FrameLayout playercontrolerview;
View view_full_cc;
TextView tv_subtitleText;
private static Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoview = (VideoView) findViewById(R.id.VideoView);
tv_subtitleText=(TextView) findViewById(R.id.tv_subtitleText);
try {
// Start the MediaController
setVideoView();
preparedvideo();
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
private void setVideoView() {
ctlr = new MediaController(MainActivity.this) {
#Override
public void show() {
repositionSubtitle(true);
super.show();
}
#Override
public void hide() {
repositionSubtitle(false);
super.hide();
}
};
playercontrolerview = (FrameLayout) ctlr.getParent();
ctlr.setMediaPlayer(videoview);
ctlr.setAnchorView(videoview);
videoview.setMediaController(ctlr);
videoview.requestFocus();
}
private void preparedvideo(){
videoview.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.samplevideo));
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
try {
mp.addTimedTextSource(getSubtitleFile(R.raw.sub1), MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
int textTrackIndex = findTrackIndexFor(MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT, mp.getTrackInfo());
if (textTrackIndex >= 0) {
try {
mp.selectTrack(textTrackIndex);
}catch (Exception e){
e.printStackTrace();
}
} else {
Log.w("subtitles", "Cannot find text track!");
}
mp.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
#Override
public void onTimedText(final MediaPlayer mp, final TimedText text) {
if(text!=null){
handler.post(new Runnable() {
#Override
public void run() {
try {
int seconds = mp.getCurrentPosition() / 1000;
Log.e("Subtitle", "subtitle Info " + text.getText());
tv_subtitleText.setText(text.getText());
}catch (Exception w){
w.printStackTrace();
}
}
});
}else{
Log.e("Subtitle", "subtitle Info null ");
}
}
});
}catch (Exception e){
e.printStackTrace();
}
try {
videoview.start();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
public void repositionSubtitle(boolean isShown) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) tv_subtitleText.getLayoutParams();
if (params != null) {
if (isShown)
params.bottomMargin = 150;
else
params.bottomMargin = 0;
tv_subtitleText.setLayoutParams(params);
}
}
private int findTrackIndexFor(int mediaTrackType, MediaPlayer.TrackInfo[] trackInfo) {
int index = -1;
for (int i = 0; i < trackInfo.length; i++) {
if (trackInfo[i].getTrackType() == mediaTrackType) {
return i;
}
}
return index;
}
private String getSubtitleFile(int resId) {
String fileName = getResources().getResourceEntryName(resId);
File subtitleFile = getFileStreamPath(fileName);
if (subtitleFile.exists()) {
Log.d("subtitle", "Subtitle already exists");
return subtitleFile.getAbsolutePath();
}
Log.d("subtitle", "Subtitle does not exists, copy it from res/raw");
// Copy the file from the res/raw folder to your app folder on the
// device
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resId);
outputStream = new FileOutputStream(subtitleFile, false);
copyFile(inputStream, outputStream);
return subtitleFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeStreams(inputStream, outputStream);
}
return "";
}
private void copyFile(InputStream inputStream, OutputStream outputStream)
throws IOException {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
// A handy method I use to close all the streams
private void closeStreams(Closeable... closeables) {
if (closeables != null) {
for (Closeable stream : closeables) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
videoview.getCurrentPosition();
// Collection<Caption> subtitles = srt.captions.values();
return false;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
#Override
public void onSeekComplete(MediaPlayer mp) {
}
}
Hi am trying to stream online radio while opening my app when buffering first time it runs fine while i close the app and then start again the app it plays from where the player last closed and then stopped after it ends and i have to startup manually to stream the url for current level of radio
my coding:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawer;
ImageView list_activity_check;
ImageView share,speaker,mute, control;
DrawerListAdapter drawerListAdapter;
ListView listview_nav;
private SmallBang mSmallBang;
String [] Items={"Program Lists","Rate app"} ;
int [] images={R.drawable.pro_logo,
R.drawable.rate_icon} ;
String[] titles = {
"Ippadikku Idhayam",
"Akilam 360",
"Cine Pattarai",
"Palsuvai Thoranam",
"Pesum Noolagam",
"Lollu Cafe",
"Kavi Saagaram",
"Aa muthal Akk",
"Thiraicholai",
"Kathamba Saaral",
"Paarkatha Pakkangal",
"Pagadi Panna Porom",
};
public static final String[] fromtime = new String[]{"10:30 AM","12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM"};
public static final String[] totime = new String[]{"12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM","10:30 AM"};
Integer[] images0 = {
R.drawable.ipadikku_idhayam,
R.drawable.akilam_360,
R.drawable.cine_pattarai,
R.drawable.palsuvai_thoranam,
R.drawable.pesum_noolagam,
R.drawable.lollu_cafe,
R.drawable.kavi_saagaram,
R.drawable.aa_muthal_akk,
R.drawable.thiraicholai,
R.drawable.kathamba_saaral,
R.drawable.paarkatha_pakkangal,
R.drawable.pagadi_panna_porom,
};
//************* Current Show ***************//
ListView list,lvshow;
List<Program> rowItems;
int iImageId;
String sTitle,sFrom,sTo ;
SQLiteDatabase db;
ImageView music;
int media1;
int intValue1;
AdapAdapter Adapadapter;
ArrayList<String> iTitle = null;
ArrayList<String> sQuantity = null;
ArrayList<String> sQuantity1 = null;
ArrayList<String> sImageID = null;
//***************************************//
SeekBar seekbar;
AudioManager audioManager;
MediaPlayer media, mediaPlayer;
boolean playPause = false;
boolean intialStage = true;
int intvalue ;
ImageView timer;
private static final int NOTIFICATION_ID = 1;
String URL = "http://streaming.shoutcast.com/MUKILFMRADIO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNotification();
mSmallBang = SmallBang.attach2Window(this);
list_activity_check = (ImageView) findViewById(R.id.list_view);
share = (ImageView) findViewById(R.id.share);
speaker = (ImageView) findViewById(R.id.speaker);
mute = (ImageView) findViewById(R.id.mute);
control = (ImageView) findViewById(R.id.play);
timer = (ImageView) findViewById(R.id.timer);
//************ Current show ************//
db = this.openOrCreateDatabase("MukilApp",Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS proname(ID INTEGER PRIMARY KEY AUTOINCREMENT,ImageID INTEGER,Title TEXT,FromTiming INTEGER,ToTiming INTEGER);");
rowItems = new ArrayList<Program>();
for (int i = 0; i < titles.length; i++) {
Program item = new Program(images0[i], titles[i],fromtime[i],totime[i]);
rowItems.add(item);
}
db.execSQL("DELETE FROM proname;");
lvshow = (ListView) findViewById(R.id.lvshow);
// listView.setVisibility(View.INVISIBLE);
final ProgramAdapter adapter = new ProgramAdapter(this,rowItems, false);
for (int i = 0; i < adapter.getCount(); i++) {
Program rowItem = (Program) adapter.getItem(i);
iImageId = rowItem.getImageId();
sTitle = rowItem.getTitle();
sFrom = rowItem.getFromtime();
sTo = rowItem.getTotime();
db.execSQL("INSERT INTO proname (ImageID,Title,FromTiming,ToTiming) VALUES(" + iImageId + ",'" + sTitle + "','" + sFrom + "','" + sTo + "');");
}
final Cursor cView = db.rawQuery("SELECT * FROM proname WHERE FromTiming <= time('now', 'localtime')\n" + "" +
"AND ToTiming >= time('now', 'localtime')\n", null);
if (cView.getCount() > 0) {
sImageID = new ArrayList<String>();
iTitle = new ArrayList<String>();
sQuantity = new ArrayList<String>();
sQuantity1 = new ArrayList<String>();
while (cView.moveToNext()) {
sImageID.add(cView.getString(1));
iTitle.add(cView.getString(2));
sQuantity.add(cView.getString(3));
sQuantity1.add(cView.getString(4));
Adapadapter = new AdapAdapter(this, sImageID, iTitle, sQuantity, sQuantity1);
lvshow.setAdapter(Adapadapter);
}
}
//*************************************//
timer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, Timer_Activity.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
// startActivity(slideactivity, bndlanimation);
startActivityForResult(slideactivity, 1001,bndlanimation);
// finish();
}
});
}
});
media = MediaPlayer.create(this,R.raw.mukil_master_jingle);
media.start();
media.setLooping(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (intialStage) {
new Player()
.execute(URL);
}
intvalue = mediaPlayer.getAudioSessionId();
control.setBackgroundResource(R.drawable.pause);
control.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (playPause == false) {
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
new Player().cancel(true);
media.stop();
media.reset();
mediaPlayer.reset();
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
media.stop();
playPause = true;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute(URL);
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = false;
}
}
});
speaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
media.setVolume(0, 0);
mediaPlayer.setVolume(0, 0);
speaker.setImageResource(R.drawable.speaker);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
}
});
mute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
media.setVolume(1, 1);
mediaPlayer.setVolume(1, 1);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false); // hide built-in Title
}
try {
seekbar = (SeekBar) findViewById(R.id.seekbar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
seekbar.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);
}
});
} catch (Exception e) {
e.printStackTrace();
}
listview_nav = (ListView) findViewById(R.id.listview_nav);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
drawerListAdapter = new DrawerListAdapter(MainActivity.this, Items, images);
listview_nav.setAdapter(drawerListAdapter);
listview_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
Intent in = new Intent(MainActivity.this,ShowList_Activity.class);
startActivity(in);
}else if(position == 1){
}
}
});
list_activity_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list_activity_check.setImageResource(R.drawable.playlist);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, EqualizerActivity.class);
slideactivity.putExtra("sessionvalue", intvalue);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
startActivity(slideactivity, bndlanimation);
}
});
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
share.setImageResource(R.drawable.share_icon);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm" + " Mukil FM shareApp");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
if(mediaPlayer == null){//check mp
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
if(media==null){//check mp
if(!media.isPlaying()){
media.start();
}
}
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void addNotification() {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mukil)
.setContentTitle("MUKIL FM")
.setContentText("Smartah Kelunga Ungal MukilFm");
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
intialStage = true;
playPause = false;
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
mediaPlayer.prepareAsync();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mediaPlayer.start();
media.stop();
intialStage = false;
}
public Player() {
progress = new ProgressDialog(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
media.start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
String result=data.getStringExtra("result");
if(result.equalsIgnoreCase("STOP")){
onStop();
finish();
}else if(result.equalsIgnoreCase("Do Nothing")){
Toast.makeText(this, "Timer is not set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStop() {
super.onStop();
if(media != null){
// media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
// mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
MainActivity.this.finish();
mediaPlayer.release();
media.release();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// super.onBackPressed();
}
}
please help me in fixing this issues..
Thank you in advance..
In your onStop() of your activity stop and release the media player.
Place the below code in your onStop():
#Override
public void onStop() {
super.onStop();
if(media != null){
media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
This is the proper way to stop media player.
Hope it helps:)
I have listview which contains a list of audio files with play button and seekbar. I displayed the listview using base adapter.
When I click a play button of a listview I want to play an audio file. I successfully implemented this but when i click another play button in list two audio files are playing continuously, It will continue for all onclick of play button. How can I restrict the mediaplayer to play in one position and if I click a another icon it have to stop the old media player and start to play the new one. Can anyone say me how do I implement this ?
Hi I am using this code
public class PlayerList extends Activity {
private static final String TAG = "log";
ListView listV;
ArrayList<HashMap<String, String>> arrList = new ArrayList<HashMap<String,String>>();;
String[] strArray = { "/mnt/sdcard/Nal.mp3", "/mnt/sdcard/Nal2.mp3",
"/mnt/sdcard/Nal3.mp3", "/mnt/sdcard/sample1.mp3", };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
listV = (ListView) findViewById(R.id.HomePagelistView1);
for (int i = 0; i < strArray.length; i++) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("title", "File Name");
hmap.put("description", "File description");
hmap.put("url", strArray[i]);
arrList.add(hmap);
}
FileListAdapter sAdapter = new FileListAdapter(arrList, PlayerList.this);
listV.setAdapter(sAdapter);
}
}
And the FileListAdapter file is given below
public class FileListAdapter extends BaseAdapter implements
OnCompletionListener, OnSeekBarChangeListener {
private MediaPlayer mp;
private Handler mHandler = new Handler();;
private Utilities utils;
SeekBar seekBar;// = (SeekBar) findViewById(R.id.homeList_seekBar1);
String songPath = "";
// ImageView imageVPlay;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
public FileListAdapter(ArrayList<HashMap<String, String>> data,
Context context) {
this.data = data;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.homelist, parent, false);
final ImageView imageVDownload = (ImageView) vi
.findViewById(R.id.homeListimageDownload); // download
final ImageView imageVPlay = (ImageView) vi
.findViewById(R.id.homeListimagePlay); // play
final TextView textVTitle = (TextView) vi
.findViewById(R.id.homeListTextTitle); // email ID
final TextView textVDescription = (TextView) vi
.findViewById(R.id.homeListTextDesc); // email ID
seekBar = (SeekBar) vi.findViewById(R.id.homeList_seekBar1);
textVTitle.setText(data.get(position).get("title"));
textVDescription.setText(data.get(position).get("description"));
// /////////////////////////////////// set image tick and download
String loadFilePath = data.get(position).get("url");
// String loadFileName = data.get(position).get("title");
File ffPath = new File(loadFilePath);
String loadfileNameWithExt = ffPath.getName();
Log.i(TAG, "load file and name path " + " " + loadfileNameWithExt
+ " " + loadFilePath);
imageVPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String selectFilePath = data.get(position).get("url");
String selectFileName = data.get(position).get("title");
Log.i(TAG, "selected file and name path " + selectFileName
+ " " + selectFilePath);
songPath = selectFilePath;
mediaplayerMethod(selectFilePath);
imageVPlay.setImageResource(R.drawable.list_pause);
textVTitle.setVisibility(View.INVISIBLE);
textVDescription.setVisibility(View.INVISIBLE);
seekBar.setVisibility(View.VISIBLE);
}
});
return vi;
}
protected void mediaplayerMethod(String filepath) {
Log.d(TAG, "mediaplayerMethod audio file path " + filepath);
mp = new MediaPlayer();
mp.setOnCompletionListener(FileListAdapter.this); // Important
seekBar.setOnSeekBarChangeListener(FileListAdapter.this);
utils = new Utilities();
playSong(filepath);
}
private void playSong(final String fileptath) {
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
String xmlString = (String) message.obj;
Log.d(TAG, "handleMessage ");
try {
// mp.prepare();
mp.start();
seekBar.setProgress(0);
seekBar.setMax(100);
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread() {
#Override
public void run() {
Log.d(TAG, "run ");
try {
mp.reset();
mp.setDataSource(fileptath);
Log.i(TAG, "internal file");
mp.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message message = handler.obtainMessage(1, "");
handler.sendMessage(message);
}
};
thread.start();
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int) (utils.getProgressPercentage(
currentDuration, totalDuration));
seekBar.setProgress(progress);
try {
double progVal = (progress / 100.0) * (360.0);
int progInt = (int) Math.ceil(progVal);
} catch (NumberFormatException e) {
Log.e(TAG, "NumberFormatException " + e);
}
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException " + e);
}
}
};
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.release();
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
updateProgressBar();
}
}// FileListAdapter
Release your old MediaPlayer when You going to start a new instance. For example:
protected void mediaplayerMethod(String filepath) {
Log.d(TAG, "mediaplayerMethod audio file path " + filepath);
if(mp != null){
mp.release();
}
mp = null;
mp = new MediaPlayer();
mp.setOnCompletionListener(FileListAdapter.this); // Important
seekBar.setOnSeekBarChangeListener(FileListAdapter.this);
utils = new Utilities();
playSong(filepath);
}
I have this adapter and I'm trying to display progress dialog when media player is preparing. But for some reason my dialog wont show. Can anybody tell me where I'm wrong? Also I don't get any logCat error output.
Here is my Adapter:
public class AlbumDetailsAdapter extends BaseAdapter {
private Activity activity;
private static ArrayList<Songs> data;
private static LayoutInflater inflater = null;
private MediaPlayer mediaPlayer;
private ImageView playSong;
private Albums album;
private ImageLoader loader;
private int oldPosition = -1;
private DatabaseHelper helper;
private ImageView downloadSong;
private boolean exists;
Handler handler = new Handler();
public AlbumDetailsAdapter(Activity a, ArrayList<Songs> products,
Albums album) {
activity = a;
this.album = album;
loader = new ImageLoader(activity);
mediaPlayer = new MediaPlayer();
data = products;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public void stopMusic() {
try {
mediaPlayer.stop();
} catch (Exception e) {
}
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
final ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.songs_items, parent, false);
ImageView songthums = (ImageView) vi.findViewById(R.id.song_item_thumb);
TextView singer = (TextView) vi
.findViewById(R.id.songs_item_album_singer);
TextView songNumber = (TextView) vi
.findViewById(R.id.songs_item_number);
TextView albumTitle = (TextView) vi
.findViewById(R.id.songs_item_album_title);
TextView feat = (TextView) vi.findViewById(R.id.songs_item_feat);
feat.setText(data.get(position).getFeat());
if (data.get(position).getFeat().length() <= 1) {
feat.setVisibility(View.GONE);
}
singer.setText(data.get(position).getSONG_ARTIST());
loader.DisplayImage(data.get(position).getSONG_THUMB(), songthums);
helper = new DatabaseHelper(activity);
helper.openDB();
playSong = (ImageView) vi.findViewById(R.id.songs_item_play);
downloadSong = (ImageView) vi.findViewById(R.id.songs_item_download);
if (helper.getDownloadedSong(album.getTAG_ID(), data.get(position)
.getSONG_TITLE())) {
Log.v("--", "Y");
downloadSong.setBackgroundResource(R.drawable.down_no);
} else
downloadSong.setBackgroundResource(R.drawable.down_yes);
helper.closeDB();
if (data.get(position).getSONG_MP3().length() > 0) {
if (!data.get(position).getIsPlaying())
playSong.setBackgroundResource(R.drawable.play_nr);
else
playSong.setBackgroundResource(R.drawable.stop);
} else
playSong.setBackgroundResource(R.drawable.play_pr);
downloadSong.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!helper.isDBOpen()) {
helper.openDB();
}
if (helper.isSongShared(data.get(position).getSONG_TITLE()
.toString().replace("'", ""), album.getTAG_ID())) {
if (helper.getDownloadedSong(album.getTAG_ID(),
data.get(position).getSONG_TITLE())) {
Toast.makeText(activity,
R.string.song_already_downloaded,
Toast.LENGTH_SHORT).show();
}
} else {
shareAlbum(data.get(position).getSONG_TITLE(),
album.getTAG_ID(), position);
}
helper.closeDB();
}
});
playSong.setOnClickListener(new OnClickListener() {
// final ProgressDialog bufferingDialog = new
// ProgressDialog(activity);
final ProgressDialog bufferingDialog = new ProgressDialog(
activity);
#Override
public void onClick(View v) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
try {
mediaPlayer.stop();
((AlbumDetails) activity).changePicToPlay(position);
if (oldPosition != position) {
bufferingDialog.setMessage(activity
.getString(R.string.buffering));
bufferingDialog.show();
((AlbumDetails) activity)
.changePicToPlay(oldPosition);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(data.get(position)
.getSONG_MP3());
mediaPlayer.prepare();
mediaPlayer.start();
postData(1, position);
// on complete
mediaPlayer
.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(
MediaPlayer mp) {
mediaPlayer.stop();
((AlbumDetails) activity)
.changePicToPlay(position);
}
});
bufferingDialog.dismiss();
} catch (IOException e) {
Log.v("--", "padna menuvam vo stop");
((AlbumDetails) activity)
.changePicToPlay(position);
mediaPlayer.stop();
bufferingDialog.dismiss();
Toast.makeText(activity,
"Song not existing",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
/*
* if (bufferingDialog.isShowing())
* bufferingDialog.dismiss();
*/
// mediaPlayer.release();
Log.v("--", "played before1");
} catch (Exception e) {
}
} else {
if (data.get(position).getIsPlaying()) {
Log.v("--", "played before0");
mediaPlayer.stop();
Log.v("--", "sviri smeni vo stop");
((AlbumDetails) activity)
.changePicToPlay(position);
if (bufferingDialog.isShowing())
bufferingDialog.dismiss();
} else {
Log.v("--", "not played before");
bufferingDialog.setMessage(activity
.getString(R.string.buffering));
bufferingDialog.show();
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(data.get(position)
.getSONG_MP3());
((AlbumDetails) activity).changePicToPlay(position);
mediaPlayer.prepare();
mediaPlayer.start();
postData(1, position);
// on complete
mediaPlayer
.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
((AlbumDetails) activity)
.changePicToPlay(position);
}
});
bufferingDialog.dismiss();
} catch (IOException e) {
Log.v("--", "padna menuvam vo stop");
((AlbumDetails) activity)
.changePicToPlay(position);
mediaPlayer.stop();
Toast.makeText(activity,
"Song not existing",
Toast.LENGTH_SHORT).show();
bufferingDialog.dismiss();
e.printStackTrace();
}
}
}
oldPosition = position;
}
});
ImageView youtube = (ImageView) vi.findViewById(R.id.songs_item_video);
if (data.get(position).getSONG_MP4().length() > 0) {
youtube.setBackgroundResource(R.drawable.video_nr);
youtube.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
postData(2, position);
Intent intent;
if (!data.get(position).getSONG_MP4().startsWith("http://")) {
intent = new Intent(Intent.ACTION_VIEW, Uri
.parse("http://"
+ data.get(position).getSONG_MP4()));
} else {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(data
.get(position).getSONG_MP4()));
}
v.getContext().startActivity(intent);
}
});
}
albumTitle.setText(Html.fromHtml(data.get(position).getSONG_TITLE()));
singer.setText(Html.fromHtml(data.get(position).getSONG_ARTIST()));
// songNumber.setText(position + 1 + "");
songNumber.setVisibility(View.GONE);
helper.closeDB();
return vi;
}
private void shareAlbum(final String songId, final String albumID,
final int position) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Intent i = new Intent(activity.getApplicationContext(),
ShareOnFacebook.class);
i.putExtra("songs", data.get(position));
i.putExtra("album", album);
i.putExtra("position", position);
activity.startActivity(i);
if (!helper.isDBOpen())
helper.openDB();
if (helper == null) {
helper = new DatabaseHelper(activity);
helper.openDB();
}
if (mediaPlayer.isPlaying()) {
((AlbumDetails) activity).changePicToPlay(position);
}
helper.addSharedSong(songId, albumID);
helper.closeDB();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(
activity.getString(R.string.do_you_want_to_share_this_song_on_facebook_))
.setPositiveButton(activity.getString(R.string.yes),
dialogClickListener)
.setNegativeButton(activity.getString(R.string.no),
dialogClickListener).show();
}
public void exists(boolean b) {
exists = b;
}
public void toastMsg() {
Toast.makeText(activity,
activity.getString(R.string.song_not_available),
Toast.LENGTH_SHORT).show();
}
public boolean getExists() {
return exists;
}
public boolean isSongAvailable(final int position) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(data
.get(position).getSONG_MP3()).openConnection();
con.setRequestMethod("HEAD");
exists(false);
} catch (Exception e) {
e.printStackTrace();
exists(true);
}
return null;
}
protected void onPostExecute(Void result) {
if (getExists() == false) {
toastMsg();
}
};
}.execute();
return getExists();
}
public static void postData(final int choice, final int position) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://nelu.burduja.com/musica/counting_song.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
switch (choice) {
case 1:
nameValuePairs.add(new BasicNameValuePair(
"song_streaming", "1"));
nameValuePairs.add(new BasicNameValuePair("song_id",
data.get(position).getSONG_ID()));
break;
case 2:
nameValuePairs.add(new BasicNameValuePair("song_video",
"1"));
nameValuePairs.add(new BasicNameValuePair("song_id",
data.get(position).getSONG_ID()));
break;
case 3:
nameValuePairs.add(new BasicNameValuePair(
"song_download", "1"));
nameValuePairs.add(new BasicNameValuePair("song_id",
data.get(position).getSONG_ID()));
break;
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
#SuppressWarnings("unused")
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
}.execute();
}
}
After 2 hours of searching and looking at my code I finally got the answer... I need to put the dialog.dismiss() in my mediaPlayer's setOnPreparedListener