Implementing audio player in listview in android - android

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);
}

Related

Show progress bar while loading audio file

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!!

How to stop media player start and stop media player properly in android?

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:)

MediaPlayer slowing down listview

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();
}
});

Video stops and goes to initial stage after exiting full screen to normal screen

I am working on a video player where I have used custom play/pause, fullscreen etc control buttons for normal screen and default media controller for full screen, which I have customized by adding a control button so that the full screen can be exited and switch back to normal small screen. I am able to full screen the video, but once I click that control button in full screen mode, the video stops and goes back to initial state, though the full screen can be switched to normal screen mode. What I should I do or change in my code so that the video can continue playing? I am searching google for the past three hours still could not find an exact solution. :(
Here is my code:
VideoFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
frame = (FrameLayout)rootView.findViewById(R.id.frame);
frame2 = (FrameLayout)rootView.findViewById(R.id.frame2);
frame3 = (FrameLayout)rootView.findViewById(R.id.frame3);
marquee = (TextView)rootView.findViewById(R.id.marquee);
marquee.setSelected(true);//focusing the marquee
video = (VideoView) rootView.findViewById(R.id.videoview1);
seekBar = (SeekBar)rootView.findViewById(R.id.seekBar1);
runtime = (TextView)rootView.findViewById(R.id.runtime);
current = (TextView)rootView.findViewById(R.id.current);
list = (ListView)rootView.findViewById(R.id.list);
//list.setTextFilterEnabled(true);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// _context=this;
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)rootView.findViewById(R.id.play);
back = (ImageButton)rootView.findViewById(R.id.prev);
next = (ImageButton)rootView.findViewById(R.id.next);
full = (ImageButton)rootView.findViewById(R.id.full);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
full.setOnClickListener(this);
//action bar controls
bar = getActivity().getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
//bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
seekBar.setBackgroundColor(Color.BLACK);
seekBar.setProgressDrawable(getResources().getDrawable( R.drawable.seekbar));
seekBar.setScaleY(1f);
ShapeDrawable thumb = new ShapeDrawable(new OvalShape());
thumb.getPaint().setColor(Color.CYAN);
thumb.setIntrinsicHeight(20);
thumb.setIntrinsicWidth(20);
seekBar.setThumb(thumb);
EditText editText = new EditText(getActivity().getApplicationContext());
getActivity().getActionBar().setCustomView(editText);
Scanner("/sdcard/");//storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
listAdapter=new VideoListAdapter(getActivity().getApplicationContext(),listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
dm=new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
//////////////////changing list item background on click///////////////////
list.setVisibility(View.GONE);
//frame = (FrameLayout)view.findViewById(R.id.frame);
//video = (VideoView) view.findViewById(R.id.videoview1);
//list.setSelection(position);
view.setSelected(true);
///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
list.clearChoices();
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
selected_item=position;
// view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
//accessing song path
list.setItemChecked(position, true);
list.setSelection(position);
//accessing the song name
String name = (String) ((TextView) view).getText();
title = name;
marquee.setText(title);
//bar.setTitle(title);
//Log.e(TAG, name);
//Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
index = position;
play.setImageResource(R.drawable.pause);
frame2.setVisibility(View.VISIBLE);
frame3.setVisibility(View.VISIBLE);
frame.setVisibility(View.VISIBLE); ///is this the problem?
video.setVideoPath(listTest.get(position));
video.requestFocus();
video.start();
video.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play.setImageResource(R.drawable.play);
video.stopPlayback();
video.clearFocus();
list.setVisibility(View.VISIBLE);
frame.setVisibility(View.GONE);
//seekBar.refreshDrawableState();
frame2.setVisibility(View.GONE);
frame3.setVisibility(View.GONE);
}
});
}
catch(Exception e){e.printStackTrace();}
video.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(video.getDuration());
seekBar.postDelayed(onEverySecond, 1000);
time= video.getDuration();
long sec = (time / 1000) % 60;
long min = (time / (60 * 1000))%60;
long hour = time / (60 * 60 * 1000);
String s = (sec < 10) ? "0" + sec : "" + sec;
String m = (min < 10) ? "0" + min : "" + min;
String h = "" + hour;
String time = "";
if(hour > 0) {
time = h + ":" + m + ":" + s;
} else {
time = m + ":" + s;
}
runtime.setText(""+time);
}
});
}
});
}
return rootView;
}
private Runnable onEverySecond=new Runnable() {
#Override
public void run() {
if(seekBar != null) {
seekBar.setProgress(video.getCurrentPosition());
run = video.getCurrentPosition();
long sec2 = (run / 1000) % 60;
long min2 = (run / (60 * 1000))%60;
long hour2 = run / (60 * 60 * 1000);
String s2 = (sec2 < 10) ? "0" + sec2 : "" + sec2;
String m2 = (min2 < 10) ? "0" + min2 : "" + min2;
String h2 = "" + hour2;
String run = "";
if(hour2 > 0) {
run = h2 + ":" + m2 + ":" + s2;
} else {
run = m2 + ":" + s2;
}
current.setText(""+run);
}
if(video.isPlaying()) {
seekBar.postDelayed(onEverySecond, 1000);
}
}
};
///////////////////orientation change//////////////////////
/* #Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(getActivity().getApplicationContext(), "landscape", Toast.LENGTH_SHORT).show();
video.setLayoutParams(new FrameLayout.LayoutParams(600,270));//changing layout size
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(getActivity().getApplicationContext(), "portait", Toast.LENGTH_SHORT).show();
video.setLayoutParams(new FrameLayout.LayoutParams(350, dm.widthPixels));//changing layout size
}
}*/
/////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp4"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(video.isPlaying())
{
video.pause();
progress=video.getCurrentPosition();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
video.start();
seekBar.setProgress(video.getCurrentPosition());
seekBar.setMax(video.getDuration());
seekBar.postDelayed(onEverySecond, 1000);
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
video.stopPlayback();
video.refreshDrawableState();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
selected_item=index;
listAdapter.notifyDataSetChanged();//shifting the highlight to the song played
}
else
{
index = (list.getAdapter().getCount()-1);
selected_item=index;
listAdapter.notifyDataSetChanged();
}
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
//mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
video.setVideoURI(uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
}
try {
//video.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
video.start();
title = uri.getLastPathSegment();
marquee.setText(title);
play.setImageResource(R.drawable.pause);
}
if (v.equals(next))
{
video.stopPlayback();
video.refreshDrawableState();
index = index +1;
if(index>(listSoundNames.size()-1))
{
index=0;
}
play.setImageResource(R.drawable.pause);
//index = index +1;
selected_item=index;
listAdapter.notifyDataSetChanged();
//Toast.makeText(MP3.this, ""+selected_item, Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
//mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
video.setVideoURI(uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
}
try {
//mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
video.start();
title = uri.getLastPathSegment();
marquee.setText(title);
}
if(v.equals(full))
{
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
/*Uri uri = Uri.parse(listTest.get(index).toString());
Toast.makeText(getApplicationContext(), "full", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW );
intent.setDataAndType((uri), "video/*");
startActivity(intent);*/
Intent intent = new Intent(getActivity().getApplicationContext(),Full.class);
Bundle b2 = new Bundle();
b2.putString("path", uri.toString());
b2.putInt("progress", video.getCurrentPosition());
intent.putExtras(b2);
this.startActivity(intent);
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if(fromUser) {
// this is when actually seekbar has been seeked to a new position
video.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
int progress = seekBar.getProgress();
if (video != null && video.isPlaying()) {
// Set the position of the currently playing
video.seekTo(progress);
}
}
///////////////////////////stopping the current audio/video when tab is swiped/////////////////////////////////
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// Make sure that we are currently visible
if (this.isVisible()) {
// If we are becoming invisible, then...
///video.start();
//Log.e("MyFragment", "Visible again. Starting audio.");
//video.clearFocus();
//play.setImageResource(R.drawable.pause);
if (!isVisibleToUser) {
Log.e("MyFragment", "Not visible anymore. Stopping audio.");
// TODO stop audio playback
/* play.setImageResource(R.drawable.play);
video.stopPlayback();
video.clearFocus();
list.setVisibility(View.VISIBLE);
frame.setVisibility(View.GONE);
//seekBar.refreshDrawableState();
frame2.setVisibility(View.GONE);
*/
//video.stopPlayback();
video.pause();
//video.clearFocus();
play.setImageResource(R.drawable.play);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Full.java// for the full screen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullsc);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
Bundle bundle = getIntent().getExtras();
path = bundle.getString("path");
pos = bundle.getInt("progress");
Uri uri = Uri.parse(path);
video = (VideoView) findViewById(R.id.fullv);
getActionBar().hide();
/* video.setMediaController(new MediaController(this){
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
((Activity) getContext()).finish();
return super.dispatchKeyEvent(event);
}
});*/
controller = new CMediaController(this);
/* controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
//next button clicked
Toast.makeText(getApplicationContext(), "next", Toast.LENGTH_SHORT).show();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
v.requestLayout();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
//previous button clicked
Toast.makeText(getApplicationContext(), "prev", Toast.LENGTH_SHORT).show();
}
});*/
video.setMediaController(controller);
video.setVideoURI(uri);
video.seekTo(pos);
video.requestFocus();
video.start();
}
}
fullsc.xml//layout for full screen
<?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"
android:orientation="vertical"
android:background="#000000">
<VideoView
android:layout_gravity="center"
android:id="#+id/fullv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:keepScreenOn="true"
/>
</LinearLayout>
CMediaController.java // for the media controller customization
public class CMediaController extends MediaController {
Context mContext;
//private OnMediaControllerInteractionListener mListener;
public CMediaController(Context context) {
super(context);
// TODO Auto-generated constructor stub
mContext = context;
}
#Override
public void setAnchorView(View view) {
super.setAnchorView(view);
ImageButton full = new ImageButton(mContext);
full.setBackgroundResource(R.id.full);
full.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
//next button clicked
Toast.makeText(mContext, "return to small", Toast.LENGTH_SHORT).show();
((Activity) getContext()).finish();//exiting but stopping the video and setting it to initial state
/*
Intent intent = new Intent(mContext,VideoFragment.class);
//Bundle b2 = new Bundle();
b2.putString("path", uri.toString());
b2.putInt("progress", video.getCurrentPosition());
intent.putExtras(b2);
mContext.startActivity(intent);*/
}}));
/*full = (ImageButton)findViewById(R.id.full);*/
//full.setOnClickListener(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
addView(full, params);
}
/*#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "small", Toast.LENGTH_SHORT).show();
}*/
}

I have 2 activities. I need to play one background music to all the activities.I want play and stop song from main activity

This is my main activity which is actually a tab activity. I am choosing list of song and i am trying to play radio in activity given below.
public class MainActivity extends TabActivity {
String[] actions = new String[] { "Tune-Up", "About Us", "Like-Us",
"Other", "Exit" };
Spinner country_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
TabHost tabHost = getTabHost();
TabSpec allcallspec = tabHost.newTabSpec("listner");
allcallspec.setIndicator("listener");
Intent allIntent = new Intent(this, Tab_Listner.class);
allcallspec.setContent(allIntent);
// Tab for recived call
TabSpec recivespec = tabHost.newTabSpec("Like");
// setting Title and Icon for the Tab
recivespec.setIndicator("Like");
Intent reciveIntent = new Intent(MainActivity.this, Tab_Like.class);
recivespec.setContent(reciveIntent);
TabSpec recivespec1 = tabHost.newTabSpec("Categery");
// setting Title and Icon for the Tab
recivespec1.setIndicator("CateGories");
Intent reciveIntent1 = new Intent(MainActivity.this,
Category_name.class);
recivespec1.setContent(reciveIntent1);
tabHost.addTab(recivespec);
tabHost.addTab(allcallspec); // Adding photos tab
// Adding songs tab
tabHost.addTab(recivespec1); // Adding songs tab
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// MenuItem mainMenuSpinner = menu.findItem( R.id.menu_main_spinner);
// setupMainMenuSpinner( mainMenuSpinner );
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
getMenuInflater().inflate(R.menu.mainactivity, menu);
Log.i("Android Version is", "Belove Froyo Action Bar Not Displayed");
MenuItem statusSpinner = menu.findItem(R.id.menu_status_spinner);
setupStatusSpinner(statusSpinner);
}
return super.onCreateOptionsMenu(menu);
}
private void setupStatusSpinner(MenuItem item) {
View view = item.getActionView();
if (view instanceof Spinner) {
Spinner spinner = (Spinner) view;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, actions);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
switch (arg2) {
case 1:
Log.i("About US", "Go");
startActivity(new Intent(MainActivity.this,
About_Us.class));
break;
case 2:
String url = "https://www.facebook.com/musicbreeds";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
break;
case 3:
Log.i("Other", "Go");
startActivity(new Intent(MainActivity.this, Other.class));
break;
case 4:
Log.i("Exit", "unSuccess");
System.out.print("not.......................");
System.exit(0);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
TextView tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
}
}
Play_Radio activity, In this activity i play and pause songs. i want to have play/pause button at bottom in my MainActivity to stop and play current song.
public class Play_Radio extends Activity {
private ImageView playButton;
private TextView textStreamed, tv_radio_name, tv_radio_cat;
private boolean isPlaying;
private static StreamingMediaPlayer audioStreamer;
private AudioManager audioManager = null;
ImageView iv_like;
Dialog rankDialog;
RatingBar ratingBar, pre_rating;
float cus_rating;
AdView adView;
Dialog dialog;
public static String name, rating, like, radio_url, id, listner, image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.play_radio);
if (audioStreamer != null) {
try {
Log.i("Already ply", "Succss");
audioStreamer.stop();
} catch (Exception e) {
}
} else {
Log.i("First time", "Play");
}
initControls();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i("On Pause is call", "Succcess");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
getMenuInflater().inflate(R.menu.main, menu);
Log.i("Android Device above", "Home Enbled");
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.i("Home", "Press");
return true;
}
return super.onOptionsItemSelected(item);
}
private void initControls() {
iv_like = (ImageView) findViewById(R.id.iv_activity_like);
iv_like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
Toast.makeText(getApplicationContext(),
"Thanks For like Our Station", Toast.LENGTH_LONG)
.show();
}
});
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
textStreamed = (TextView) findViewById(R.id.text_kb_streamed);
playButton = (ImageView) findViewById(R.id.imageView1);
playButton.setEnabled(false);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.i("Click sadg ", "success");
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
if (audioStreamer.getMediaPlayer().isPlaying()) {
Log.i("play ", "success");
audioStreamer.getMediaPlayer().pause();
playButton.setImageResource(R.drawable.play_radio_play);
} else {
Log.i("pause", "success");
audioStreamer.getMediaPlayer().start();
audioStreamer.startPlayProgressUpdater();
playButton.setImageResource(R.drawable.play_radio_pause);
}
isPlaying = !isPlaying;
}
});
// rating radio sation
ImageView rankBtn = (ImageView) findViewById(R.id.iv_activity_rating);
rankBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rankDialog = new Dialog(Play_Radio.this,
R.style.FullHeightDialog);
rankDialog.setContentView(R.layout.rating_bar);
rankDialog.setCancelable(true);
ratingBar = (RatingBar) rankDialog
.findViewById(R.id.dialog_ratingbar);
float userRankValue = 0;
// ratingBar.setRating(userRankValue);
ratingBar
.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromUser) {
// TODO Auto-generated method stub
cus_rating = rating;
}
});
Button updateButton = (Button) rankDialog
.findViewById(R.id.rank_dialog_button);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Play_Radio.this,
"Thanks For Rating Our Stations",
Toast.LENGTH_LONG).show();
rankDialog.dismiss();
}
});
// now that the dialog is set up, it's time to show it
rankDialog.show();
}
});
String urlstring2 = Tab_Listner.radio_url;
Toast.makeText(Play_Radio.this, "Please Wait...", Toast.LENGTH_LONG)
.show();
startStreamingAudio(urlstring2);
tv_radio_cat = (TextView) findViewById(R.id.tv_play_radio_cat);
tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
pre_rating = (RatingBar) findViewById(R.id.ratingBar1);
pre_rating.setRating(Float.parseFloat(Tab_Listner.rating));
}
private void startStreamingAudio(String urlstring) {
try {
dialog = new Dialog(Play_Radio.this,
android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.progress_layout);
dialog.setTitle("loading...");
dialog.show();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
if (audioStreamer != null) {
audioStreamer.interrupt();
}
audioStreamer = new StreamingMediaPlayer(this, textStreamed,
playButton, progressBar, dialog);
audioStreamer.startStreaming(urlstring, 5208, 216);
} catch (Exception e) {
Log.e(getClass().getName(), "Error starting to stream audio.", e);
}
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
private Integer[] mImageIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
}
i have already add play/pause button in playradio activity and its work but i want to play pause button on mainactivity for start and stop play song which are already play run in to radio activity
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96 * 10 / 8;// assume
// 96kbps*10secs/8bits
// per byte
private TextView textStreamed;
private ImageView playButton;
private Dialog dialog;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;
private int totalKbRead = 0;
// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();
private MediaPlayer mediaPlayer;
private File downloadingMediaFile;
private boolean isInterrupted;
private Context context;
private int counter = 0;
public StreamingMediaPlayer(Context context, TextView textStreamed,
ImageView playButton, ProgressBar progressBar, Dialog dialog) {
this.context = context;
this.textStreamed = textStreamed;
this.playButton = playButton;
this.progressBar = progressBar;
this.dialog = dialog;
}
public void startStreaming(final String mediaUrl, long mediaLengthInKb,
long mediaLengthInSeconds) throws IOException {
this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;
Runnable r = new Runnable() {
public void run() {
// Dialog dialog=null;
try {
downloadAudioIncrement(mediaUrl);
} catch (IOException e) {
Log.e(getClass().getName(),
"Unable to initialize the MediaPlayer for fileUrl="
+ mediaUrl, e);
return;
}
}
};
new Thread(r).start();
}
public void downloadAudioIncrement(String mediaUrl) throws IOException {
URLConnection cn = new URL(mediaUrl).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {
Log.e(getClass().getName(),
"Unable to create InputStream for mediaUrl:" + mediaUrl);
}
downloadingMediaFile = new File(context.getCacheDir(),
"downloadingMedia.dat");
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead / 1000;
testMediaBuffer();
fireDataLoadUpdate();
} while (validateNotInterrupted());
stream.close();
if (validateNotInterrupted()) {
fireDataFullyLoaded();
}
}
private boolean validateNotInterrupted() {
if (isInterrupted) {
if (mediaPlayer != null) {
mediaPlayer.pause();
// mediaPlayer.release();
}
return false;
} else {
return true;
}
}
private void testMediaBuffer() {
Runnable updater = new Runnable() {
public void run() {
if (mediaPlayer == null) {
// Only create the MediaPlayer once we have the minimum
// buffered data
if (totalKbRead >= INTIAL_KB_BUFFER) {
try {
startMediaPlayer();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error copying buffered conent.", e);
}
}
} else if (mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000) {
transferBufferToMediaPlayer();
}
}
};
handler.post(updater);
}
private void startMediaPlayer() {
try {
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
moveFile(downloadingMediaFile, bufferedFile);
Log.e(getClass().getName(),
"Buffered File path: " + bufferedFile.getAbsolutePath());
Log.e(getClass().getName(),
"Buffered File length: " + bufferedFile.length() + "");
mediaPlayer = createMediaPlayer(bufferedFile);
// We have pre-loaded enough content and started the MediaPlayer so
// update the buttons & progress meters.
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
} catch (IOException e) {
Log.e(getClass().getName(), "Error initializing the MediaPlayer.",
e);
return;
}
}
private MediaPlayer createMediaPlayer(File mediaFile) throws IOException {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what
+ ") with extra (" + extra + ")");
return false;
}
});
FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
mPlayer.prepare();
return mPlayer;
}
private void transferBufferToMediaPlayer() {
try {
// First determine if we need to restart the player after
// transferring data...e.g. perhaps the user pressed pause
boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
// Copy the currently downloaded content to a new buffered File.
// Store the old File for deleting later.
File oldBufferedFile = new File(context.getCacheDir(),
"playingMedia" + counter + ".dat");
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
// This may be the last buffered File so ask that it be delete on
// exit. If it's already deleted, then this won't mean anything. If
// you want to
// keep and track fully downloaded files for later use, write
// caching code and please send me a copy.
bufferedFile.deleteOnExit();
moveFile(downloadingMediaFile, bufferedFile);
mediaPlayer.pause();
mediaPlayer = createMediaPlayer(bufferedFile);
mediaPlayer.seekTo(curPosition);
boolean atEndOfFile = mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile) {
mediaPlayer.start();
}
oldBufferedFile.delete();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error updating to newly loaded content.", e);
}
}
private void fireDataLoadUpdate() {
Runnable updater = new Runnable() {
public void run() {
textStreamed.setText((totalKbRead + "Kb"));
float loadProgress = ((float) totalKbRead / (float) mediaLengthInKb);
progressBar.setSecondaryProgress((int) (loadProgress * 100));
if (dialog != null)
dialog.dismiss();
}
};
handler.post(updater);
}
private void fireDataFullyLoaded() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
// Delete the downloaded File as it's now been transferred to
// the currently playing buffer file.
downloadingMediaFile.delete();
textStreamed
.setText(("Audio full loaded: " + totalKbRead + " Kb read"));
}
};
handler.post(updater);
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void startPlayProgressUpdater() {
float progress = (((float) mediaPlayer.getCurrentPosition() / 1000) / mediaLengthInSeconds);
progressBar.setProgress((int) (progress * 100));
if (dialog != null)
dialog.dismiss();
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
public void interrupt() {
playButton.setEnabled(false);
isInterrupted = true;
validateNotInterrupted();
}
public void moveFile(File oldLocation, File newLocation) throws IOException {
if (oldLocation.exists()) {
BufferedInputStream reader = new BufferedInputStream(
new FileInputStream(oldLocation));
BufferedOutputStream writer = new BufferedOutputStream(
new FileOutputStream(newLocation, false));
try {
// byte[] buff = new byte[8192];
/* changing the size of the buffer */
byte[] buff = new byte[16384];
int numChars;
while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
writer.write(buff, 0, numChars);
}
} catch (IOException ex) {
throw new IOException("IOException when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
} finally {
try {
if (reader != null) {
writer.close();
reader.close();
}
} catch (IOException ex) {
Log.e(getClass().getName(),
"Error closing files when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
} else {
throw new IOException(
"Old location does not exist when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
public void change_volume(float vol) {
Log.i("Media Player volume change", "Success" + vol);
mediaPlayer.setVolume(vol, vol);
}
public void stop() {
// TODO Auto-generated method stub
mediaPlayer.stop();
}
public void stoppreviousPlayer() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
// mediaPlayer.release();
}
}
}
you need a Service which is independent to the activity to play the song
public class SongService extends Service {
MediaPlayer mm;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mm = MediaPlayer.create(this, R.raw.mainmenu2);
mm.setLooping(true);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mm.stop();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
mm.start();
}
}
then add this whenever you want to play the song in the service.
startService(new Intent(this, SongService.class));
and to finish it add this:
stopService(new Intent(MainMenu.this,SongService.class));
So when you press the button start the service, and whenever you press the stop button stop it. this is how you can play songs through activities.
First you have to create a raw folder in res folder and paste the song you want to play there.
MainActivity,java======
protected void onCreate(){
MediaPlayer backgroundSong;
backgroundSong = MediaPlayer.create(MainActivity.this, R.raw.your_song_name);
backgroundSong.start();}
#Override
protected void stopSong() {
// TODO Auto-generated method stub
backgroundSong.release();
}
OtherActivity.java
protected void onPause(){
MainActivity ma = new MainActivity();
ma.stopSong();
}

Categories

Resources