音乐播放器 mediaplayer

package com.zy.zjg;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zy.player.PlayerService;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Player extends Activity {

	private ListView listview;
	private SeekBar mSeekBar;
	private TextView txtTime;

	private ArrayList fileNames;
	private final String FOLDER = Environment.getExternalStorageDirectory() + "/zjg";
	private String now = "";
	public static boolean playing = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_player);

		listview = (ListView) findViewById(R.id.listview);
		mSeekBar = (SeekBar) findViewById(R.id.seekBar);
		txtTime = (TextView) findViewById(R.id.txtTime);

		SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.adapter_list, new String[] { "name" }, new int[] { R.id.txtName });
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView arg0, View view, int position, long arg3) {
				now = FOLDER + "/" + fileNames.get(position);
				start();
				mHandler.sendEmptyMessageDelayed(0, 1000);
			}
		});

		((ImageView) findViewById(R.id.btnPlay)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (playing) {
					pause();
				} else {
					resume();
				}
			}
		});

		((ImageView) findViewById(R.id.btnStop)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				stop();
			}
		});

		((ImageView) findViewById(R.id.btnPrev)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
			}
		});

		((ImageView) findViewById(R.id.btnNext)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
			}
		});

		mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
			}

			@Override
			public void onProgressChanged(SeekBar arg0, int position, boolean arg2) {
				int totalDuration = PlayerService.mediaPlayer.getDuration();
				seek(totalDuration * position / 100);
			}
		});

	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			int currentPosition = PlayerService.mediaPlayer.getCurrentPosition();
			int totalDuration = PlayerService.mediaPlayer.getDuration();
			mSeekBar.setProgress(currentPosition * 100 / totalDuration);
			String time = formatTime(currentPosition);
			txtTime.setText(time + "/" + formatTime(totalDuration));

			if (playing)
				mHandler.sendEmptyMessageDelayed(0, 1000);
			else
				((ImageView) findViewById(R.id.btnPlay)).setImageResource(R.drawable.play);
		};
	};

	private String formatTime(int time) {
		if (time / 1000 % 60 < 10) {
			return time / 1000 / 60 + ":0" + time / 1000 % 60;
		} else {
			return time / 1000 / 60 + ":" + time / 1000 % 60;
		}
	}

	private List> getData() {
		List> list = new ArrayList>();
		fileNames = getFiles();
		Map map = null;
		if (fileNames.size() > 0) {
			for (int i = 0; i < fileNames.size(); i++) {
				map = new HashMap();
				map.put("name", fileNames.get(i));
				list.add(map);
			}
		}

		return list;
	}

	private ArrayList getFiles() {
		ArrayList list = new ArrayList();
		File[] files = null;
		File dir = new File(FOLDER);
		if (dir.exists()) {
			files = dir.listFiles();
		}

		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				if (fileName.endsWith(".mp3"))
					list.add(files[i].getName());
			}
		}

		return list;
	}

	private void start() {
		if (now.equals(""))
			return;

		playing = true;
		((ImageView) findViewById(R.id.btnPlay)).setImageResource(R.drawable.pause);
		Intent intent = new Intent(Player.this, PlayerService.class);
		intent.putExtra("option", "start");
		intent.putExtra("path", now);
		startService(intent);
	}

	private void resume() {
		if (now.equals(""))
			return;

		playing = true;
		((ImageView) findViewById(R.id.btnPlay)).setImageResource(R.drawable.pause);
		Intent intent = new Intent(Player.this, PlayerService.class);
		intent.putExtra("option", "resume");
		intent.putExtra("path", now);
		startService(intent);
	}

	private void pause() {
		if (now.equals(""))
			return;

		playing = false;
		((ImageView) findViewById(R.id.btnPlay)).setImageResource(R.drawable.play);
		Intent intent = new Intent(Player.this, PlayerService.class);
		intent.putExtra("option", "pause");
		intent.putExtra("path", now);
		startService(intent);
	}

	private void stop() {
		playing = false;
		((ImageView) findViewById(R.id.btnPlay)).setImageResource(R.drawable.play);
		Intent intent = new Intent(Player.this, PlayerService.class);
		intent.putExtra("option", "stop");
		intent.putExtra("path", now);
		startService(intent);
	}

	private void seek(int duration) {
		Intent intent = new Intent(Player.this, PlayerService.class);
		intent.putExtra("option", "seek");
		intent.putExtra("progress", duration);
		intent.putExtra("path", now);
		startService(intent);
	}

	private void next() {
		Intent intent = new Intent(Player.this, PlayerService.class);
		intent.putExtra("option", "next");
		intent.putExtra("path", now);
		startService(intent);
	}

	private void prev() {
		Intent intent = new Intent(Player.this, PlayerService.class);
		intent.putExtra("option", "prev");
		intent.putExtra("path", now);
		startService(intent);
	}
}
package com.zy.player;

import com.zy.zjg.Player;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.os.Messenger;

public class PlayerService extends Service {
	Messenger messenger;
	public static MediaPlayer mediaPlayer;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		String option = intent.getStringExtra("option");

		if (messenger == null) {
			messenger = (Messenger) intent.getExtras().get("messenger");
		}

		if ("start".equals(option)) {
			start(intent.getStringExtra("path"));
		} else if ("pause".equals(option)) {
			pause();
		} else if ("resume".equals(option)) {
			continuePlay();
		} else if ("stop".equals(option)) {
			stop(intent.getStringExtra("path"));
		} else if ("seek".equals(option)) {
			seekPlay(intent.getIntExtra("progress", -1));
		}

		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	private void start(String path) {
		try {
			if (mediaPlayer == null)
				mediaPlayer = new MediaPlayer();
			mediaPlayer.reset();
			mediaPlayer.setDataSource(path);
			mediaPlayer.prepare();
			mediaPlayer.start();
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
				
				@Override
				public void onCompletion(MediaPlayer arg0) {
					Player.playing = false;
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void pause() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
		}
	}

	private void stop(String path) {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.stop();
			
			try {
				if (mediaPlayer == null)
					mediaPlayer = new MediaPlayer();
				mediaPlayer.reset();
				mediaPlayer.setDataSource(path);
				mediaPlayer.prepare();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void continuePlay() {
		if (mediaPlayer != null) {
			mediaPlayer.start();
		}
	}

	private void seekPlay(int seek) {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.seekTo(seek);
			mediaPlayer.start();
		}
	}
}



    

        

        

            

            
        
    

    

        

        

            

            

            

            

            

            

            
        
    




    

    







你可能感兴趣的:(音乐播放器 mediaplayer)