Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class AndroidBuildingMusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {
- private ImageButton btnPlay;
- public ArrayList<Model> mSurrahList;
- public Context mContext;
- public ListView listView;
- public TextView tvomorTitle;
- private ImageButton btnForward;
- private ImageButton btnBackward;
- private ImageButton btnNext;
- private ImageButton btnPrevious;
- private SeekBar songProgressBar;
- private TextView songTitleLabel;
- private TextView songCurrentDurationLabel;
- private TextView songTotalDurationLabel;
- private FancyAdapter mFancyAdapter;
- // Media Player
- private MediaPlayer mp;
- // Handler to update UI timer, progress bar etc,.
- private Handler mHandler = new Handler();
- private Utilities utils;
- private int seekForwardTime = 5000; // 5000 milliseconds
- private int seekBackwardTime = 5000; // 5000 milliseconds
- private long startTime = 0;
- private long finalTime = 0;
- private int currentSongIndex = 0;
- private boolean isShuffle = false;
- private boolean isRepeat = false;
- private Handler myHandler = new Handler();
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.player);
- mContext=this;
- mSurrahList=new ArrayList<Model>();
- listRawMp3List();
- listView=(ListView)findViewById(R.id.listView);
- mFancyAdapter = new FancyAdapter(mSurrahList);
- listView.setAdapter(mFancyAdapter);
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
- playSong(i);
- }
- });
- tvomorTitle=(TextView)findViewById(R.id.tvomorTitle);
- // All player buttons
- btnPlay = (ImageButton) findViewById(R.id.btnPlay);
- btnForward = (ImageButton) findViewById(R.id.btnForward);
- btnBackward = (ImageButton) findViewById(R.id.btnBackward);
- btnNext = (ImageButton) findViewById(R.id.btnNext);
- btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
- songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
- songTitleLabel = (TextView) findViewById(R.id.songTitle);
- songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
- songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
- // Mediaplayer
- mp = new MediaPlayer();
- utils = new Utilities();
- // Listeners
- songProgressBar.setOnSeekBarChangeListener(this); // Important
- mp.setOnCompletionListener(this); // Important
- // Getting all songs list
- // By default play first song
- playSong(0);
- /**
- * Play button click event
- * plays a song and changes button to pause image
- * pauses a song and changes button to play image
- * */
- btnPlay.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // check for already playing
- if(mp.isPlaying()){
- if(mp!=null){
- mp.pause();
- // Changing button image to play button
- btnPlay.setImageResource(R.drawable.btn_play);
- }
- }else{
- // Resume song
- if(mp!=null){
- mp.start();
- // Changing button image to pause button
- btnPlay.setImageResource(R.drawable.btn_pause);
- }
- }
- }
- });
- /**
- * Forward button click event
- * Forwards song specified seconds
- * */
- btnForward.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // get current song position
- int currentPosition = mp.getCurrentPosition();
- // check if seekForward time is lesser than song duration
- if(currentPosition + seekForwardTime <= mp.getDuration()){
- // forward song
- mp.seekTo(currentPosition + seekForwardTime);
- }else{
- // forward to end position
- mp.seekTo(mp.getDuration());
- }
- }
- });
- /**
- * Backward button click event
- * Backward song to specified seconds
- * */
- btnBackward.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // get current song position
- int currentPosition = mp.getCurrentPosition();
- // check if seekBackward time is greater than 0 sec
- if(currentPosition - seekBackwardTime >= 0){
- // forward song
- mp.seekTo(currentPosition - seekBackwardTime);
- }else{
- // backward to starting position
- mp.seekTo(0);
- }
- }
- });
- /**
- * Next button click event
- * Plays next song by taking currentSongIndex + 1
- * */
- btnNext.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // check if next song is there or not
- if(currentSongIndex < (mSurrahList.size() - 1)){
- playSong(currentSongIndex + 1);
- currentSongIndex = currentSongIndex + 1;
- }else{
- // play first song
- playSong(0);
- currentSongIndex = 0;
- }
- }
- });
- /**
- * Back button click event
- * Plays previous song by currentSongIndex - 1
- * */
- btnPrevious.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- if(currentSongIndex > 0){
- playSong(currentSongIndex - 1);
- currentSongIndex = currentSongIndex - 1;
- }else{
- // play last song
- playSong(mSurrahList.size() - 1);
- currentSongIndex = mSurrahList.size() - 1;
- }
- }
- });
- }
- public void listRawMp3List(){
- Field[] fields=R.raw.class.getFields();
- for(int count=0; count < fields.length; count++){
- try
- {
- int id=count;
- String name=fields[count].getName();
- String path="R.raw."+name;
- long resourceID=fields[count].getInt(fields[count]);
- mSurrahList.add(new Model(id, name, path, resourceID));
- // Toast.makeText(mContext,"resourceID:"+resourceID,Toast.LENGTH_LONG).show();
- }
- catch (Exception e)
- {
- Toast.makeText(mContext,"Exception:"+e.toString(),Toast.LENGTH_LONG).show();
- }
- }
- }
- /**
- * Function to play a song
- * @param songIndex - index of song
- * */
- public void playSong(int songIndex){
- // Play song
- try {
- mp.reset();
- // mp.setDataSource(songsList.get(songIndex).get("songPath"));
- Log.e("logg",Uri.parse("android.resource://com.androidhive.musicplayer/" + R.raw.al_ahzab).toString());
- Log.e("loggf",Uri.parse("android.resource://com.androidhive.musicplayer/" + mSurrahList.get(songIndex).getResourceID()).toString());
- Log.e("logg1",Uri.parse("android.resource://com.androidhive.musicplayer/" + mSurrahList.get(songIndex).getPath()).toString());
- // mp.setDataSource(getApplicationContext(),
- // Uri.parse("android.resource://com.androidhive.musicplayer/" + "R.raw."+mSurrahList.get(songIndex).getName()));
- mp.setDataSource(getApplicationContext(),
- Uri.parse("android.resource://com.androidhive.musicplayer/" + mSurrahList.get(songIndex).getResourceID()));
- mp.prepare();
- mp.start();
- // Displaying Song title
- String songTitle = mSurrahList.get(songIndex).getName();
- songTitleLabel.setText(songTitle);
- tvomorTitle.setText("Now playing: "+songTitle);
- // Changing Button Image to pause image
- btnPlay.setImageResource(R.drawable.btn_pause);
- // set Progress bar values
- songProgressBar.setProgress(0);
- songProgressBar.setMax(100);
- // Updating progress bar
- updateProgressBar();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalStateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Update timer on seekbar
- * */
- public void updateProgressBar() {
- mHandler.postDelayed(mUpdateTimeTask, 100);
- }
- /**
- * Background Runnable thread
- * */
- private Runnable mUpdateTimeTask = new Runnable() {
- public void run() {
- try
- {
- long totalDuration = mp.getDuration();
- long currentDuration = mp.getCurrentPosition();
- // Displaying Total Duration time
- songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
- // Displaying time completed playing
- songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
- // Updating progress bar
- int progress = utils.getProgressPercentage(currentDuration, totalDuration);
- //Log.d("Progress", ""+progress);
- songProgressBar.setProgress(progress);
- // Running this thread after 100 milliseconds
- mHandler.postDelayed(this, 100);
- }
- catch (Exception e)
- {
- }
- }
- };
- /**
- *
- * */
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
- }
- /**
- * When user starts moving the progress handler
- * */
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- // remove message Handler from updating progress bar
- mHandler.removeCallbacks(mUpdateTimeTask);
- }
- /**
- * When user stops moving the progress hanlder
- * */
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- mHandler.removeCallbacks(mUpdateTimeTask);
- int totalDuration = mp.getDuration();
- int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
- // forward or backward to certain seconds
- mp.seekTo(currentPosition);
- // update timer progress again
- updateProgressBar();
- }
- /**
- * On Song Playing completed
- * if repeat is ON play same song again
- * if shuffle is ON play random song
- * */
- @Override
- public void onCompletion(MediaPlayer arg0) {
- // check for repeat is ON or OFF
- if(isRepeat){
- // repeat is on play same song again
- playSong(currentSongIndex);
- } else if(isShuffle){
- // shuffle is on - play a random song
- Random rand = new Random();
- currentSongIndex = rand.nextInt((mSurrahList.size() - 1) - 0 + 1) + 0;
- playSong(currentSongIndex);
- } else{
- // no repeat or shuffle ON - play next song
- if(currentSongIndex < (mSurrahList.size() - 1)){
- playSong(currentSongIndex + 1);
- currentSongIndex = currentSongIndex + 1;
- }else{
- // play first song
- playSong(0);
- currentSongIndex = 0;
- }
- }
- }
- @Override
- public void onDestroy(){
- super.onDestroy();
- mp.release();
- }
- private class FancyAdapter extends BaseAdapter {
- private ArrayList<Model> mData;
- public FancyAdapter(ArrayList<Model> data) {
- mData = data;
- }
- @Override
- public int getCount() {
- return mData.size();
- }
- @Override
- public Model getItem(int position) {
- return mData.get(position);
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- TextView result;
- if (convertView == null) {
- result = (TextView) getLayoutInflater().inflate(R.layout.text_item, parent, false);
- } else {
- result = (TextView) convertView;
- }
- final String cheese = getItem(position).name;
- result.setText(cheese);
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement