How to populate listview and play audio file - android

I'am trying to populate listview from audio files and want to play the clicked item. It's not working. Any help.
MainActivity.java
public class MainActivity extends ListActivity {
public static File file;
private List<String> filelist;
ArrayList<String> MyFiles = new ArrayList<String>();
MediaPlayer mp=new MediaPlayer();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
final ListView musiclist = (ListView) findViewById(R.id.PhoneMusicList);
MyFiles = new ArrayList<String>();
final String targetPath = Environment.getExternalStorageDirectory().getAbsolutePath();
file = new File( targetPath + "/AudioRecorder" ) ;
File list[] = file.listFiles();
// Binding resources Array to ListAdapter
for( int i=0; i< list.length; i++)
{
MyFiles.add( list[i].getName() );
}
ListAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, MyFiles);
musiclist.setAdapter(adapter);
musiclist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//checking the position of item in list
Object listItem = musiclist.getItemAtPosition(position);
Toast.makeText(MainActivity.this, ""+ musiclist, Toast.LENGTH_SHORT).show();
playSong(targetPath + MyFiles.get(position));
}
});
}
private void playSong(String songPath) {
// TODO Auto-generated method stub
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/PhoneMusicList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
This is my latest layout file:
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:id="#+id/PhoneMusicList"
android:layout_width="223dp"
android:layout_height="334dp" />
<ImageView
android:id="#+id/play_pause"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/pause"/>
I have created an already functioning app which displays ListView items and when an item in the list is selected, it then opens new activity. Inside the new_activity I have TextView and Image button displaying the audio buttons which is play, pause, & stop. the TextView functions perfectly but the image buttons refused to play audio file from raw folder. I have many audio files in the raw folder and want to assign each to each ListView that will open each new activity. Please help me edit this ListViewAdapter code below to play, pause, & stop playing each audio file.
How do I edit this NewActivity.java to populate it with songs from raw folder? I will highly appreciate your support thanks.
public class NewActivity extends AppCompatActivity {
private String TAG = "NewActivity ----- ; " ;
// Store instance variables
private String title;
private int page;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
ActionBar actionBar = getSupportActionBar();
TextView mDetailTv = findViewById(R.id.textView);
//get data from previous activity when item of activity is clicked using intent
Intent intent = getIntent();
String mActionBarTitle = intent.getStringExtra("actionBarTitle");
String mContent = intent.getStringExtra("contentTv");
//setctionBar Title
actionBar.setTitle(mActionBarTitle);
//get text in text textView
mDetailTv.setText(mContent);
//ok we are done,
public void play(View v) {
if (player == null) {
player = MediaPlayer.create(this, R.raw.song_1);
Toast.makeText(this, "Tune Playing", Toast.LENGTH_SHORT ).show();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlayer();
}
});
}
player.start();
}
public void pause(View v) {
if (player != null) {
player.pause();
Toast.makeText(this, "Tune Paused", Toast.LENGTH_SHORT ).show();
}
}
public void stop(View v) {
stopPlayer();
}
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "Tune Stoped", Toast.LENGTH_SHORT ).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
}

Try with following code.
public class Recording_List extends Activity{
ListView mListView;
ImageView mPlayPause;
private File file;
private MediaPlayer mp = new MediaPlayer();
private Handler mHandler = new Handler();
private List<String> myList = new ArrayList<String>();
private static final String MEDIA_PATH = new String(
Environment.getExternalStorageDirectory() + "/AudioRecorder/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordlist);
mListView = (ListView) findViewById(R.id.recordList);
mPlayPause = (ImageView) findViewById(R.id.play_pause);
file = new File(MEDIA_PATH);
if (!file.exists()) {
file.mkdir();
}
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
playSong(MEDIA_PATH + myList.get(position));
}
});
mPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
mPlayPause.setImageResource(R.drawable.play);
}
} else {
if (mp != null) {
mp.start();
mPlayPause.setImageResource(R.drawable.pause);
}
}
}
});
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.release();
}
}

you should change targetPath as below
targetPath =targetPath + "/AudioRecorder/" ;
or replace
playSong(targetPath + MyFiles.get(position));
with
playSong(targetPath +"/AudioRecorder/"+ MyFiles.get(position));

Recorder With List View of that files in Ringa_Singa folder.
when you will stop the play you have to go back to update the list otherwise it's okay.
You can play the latest record from that play button
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_audio);
//List View
final ListView listView = (ListView) findViewById(R.id.listView);
myList = new ArrayList<String>();
//Recording events on button
startbtn = findViewById(R.id.btnRecord);
stopbtn = findViewById(R.id.btnStop);
playbtn = findViewById(R.id.btnPlay);
stopplay = findViewById(R.id.btnStopPlay);
stopbtn.setEnabled(false);
playbtn.setEnabled(false);
stopplay.setEnabled(false);
mFileName = Environment.getExternalStorageDirectory()+ "/RingaSinga";
int entryNumber = 1;
File mFile = new File(mFileName + "/RingaSinga_" + String.valueOf(entryNumber) + ".wav");
while (mFile.exists()) {
entryNumber++;
mFile = new File(mFileName + "/RingaSinga_" + String.valueOf(entryNumber) + ".wav");
}
this.mFileName = mFile.getAbsolutePath();
//List all files on list view
File directory = Environment.getExternalStorageDirectory();
mFile = new File( directory + "/RingaSinga" );
final File list[] = mFile.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, android.R.id.text1, myList);
listView.setAdapter(adapter); //Set all the file in the list.
//Click listner on List item
final File finalMFile = mFile;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(RecordAudio.this, ""+ listView, Toast.LENGTH_SHORT).show();
playSong(finalMFile + myList.get(position));
}
});
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CheckPermissions()) {
stopbtn.setEnabled(true);
startbtn.setEnabled(false);
playbtn.setEnabled(false);
stopplay.setEnabled(false);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(mFileName);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();
} else {
RequestPermissions();
}
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopbtn.setEnabled(false);
startbtn.setEnabled(true);
playbtn.setEnabled(true);
stopplay.setEnabled(true);
mRecorder.stop();
mRecorder.release();
mRecorder = null;
Toast.makeText(getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
return;
}
});
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopbtn.setEnabled(false);
startbtn.setEnabled(true);
playbtn.setEnabled(false);
stopplay.setEnabled(true);
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
Toast.makeText(getApplicationContext(), "Recording Started Playing", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
});
stopplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.release();
mPlayer = null;
stopbtn.setEnabled(false);
startbtn.setEnabled(true);
playbtn.setEnabled(true);
stopplay.setEnabled(false);
Toast.makeText(getApplicationContext(), "Playing Audio Stopped", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_AUDIO_PERMISSION_CODE:
if (grantResults.length > 0) {
boolean permissionToRecord = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean permissionToStore = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean permissionToRead = grantResults[2] == PackageManager.PERMISSION_GRANTED;
if (permissionToRecord && permissionToStore && permissionToRead) {
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean CheckPermissions() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED;
}
private void RequestPermissions() {
ActivityCompat.requestPermissions(RecordAudio.this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, REQUEST_AUDIO_PERMISSION_CODE);
}
private void playSong(String songPath) {
try {
mPlayer = new MediaPlayer();
mPlayer.reset();
mPlayer.setDataSource(songPath);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mPlayer.release();
}

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

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

android : use of media

I want to make application that gives me the list of audio files available in my SDCard and then i should be able to play that audio file from my application. And even pause resume audio playback etc. and function..
Any help on that?
You can see the below code for streaming audio from URL
private void playVideo() {
try {
final String path = "http://www.a1freesoundeffects.com/animals12557/catmeow.wav";
// If the path has not changed, just start the media player
if (path.equals(current) && mp != null) {
mp.start();
return;
}
current = path;
// Create a new media player and set the listeners
mp = new MediaPlayer();
mp.setDataSource(path);
mp.prepare();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
if (mp != null) {
mp.stop();
mp.release();
}
}
}
You can try this way.
class Mp3Filter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3"));
}
}
public class AudioPlayer extends ListActivity implements OnClickListener{
private static final String MEDIA_PATH = new String("/sdcard/backup/songs");
private List<String> songs = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
private int currentPosition = 0;
private static final String TAG = "Audio Player Demo ";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
Button playerButton;
public void onClick(View v) {
if (v.getId() == R.id.play) {
playPause();
}
}
#Override
public void onCreate(Bundle icicle) {
try {
super.onCreate(icicle);
setContentView(R.layout.songlist);
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop_label);
playerButton.setOnClickListener(this);
updateSongList();
//demoPlay();
} catch (NullPointerException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
public void updateSongList() {
File home = new File(MEDIA_PATH);
if (home.listFiles( new Mp3Filter()).length > 0) {
for (File file : home.listFiles( new Mp3Filter())) {
songs.add(file.getName());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this,R.layout.song_item,songs);
setListAdapter(songList);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
currentPosition = position;
playSong(MEDIA_PATH + songs.get(position));
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
// Setup listener so next song starts automatically
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
nextSong();}
});
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
private void nextSong() {
if (++currentPosition >= songs.size()) {
// Last song, just reset currentPosition
currentPosition = 0;
// playSong(MEDIA_PATH + songs.get(currentPosition));
} else {
// Play next song
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
private void demoPause(){
mp.pause();
playerButton.setText(R.string.play_label);
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, notPlaying);
}
// Initiate playing the media player
private void demoPlay(){
mp.start();
playerButton.setText(R.string.stop_label);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, isPlaying);
}
// Toggle between the play and pause
private void playPause() {
if(mp.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
}

Categories

Resources