做一个简单的音乐播放器

package com.siyehuazhilian.musicplay;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity implements OnClickListener {
	// ListView
	private ListView listView;
	// 适配器
	private SimpleAdapter adapter;
	// 数据源
	private ArrayList<HashMap<String, String>> list;
	// MediaPlay对象
	private MediaPlayer mediaPlayer;
	// 当前播放的曲目
	private int currentPositionMusic = -1;
	// 刷新SeekBar进度
	private static final int UPDATE_PROGRESS = 1;
	// 加载数据
	private static final int LOADING_DATA = 2;

	// 通知管理
	private NotificationManager notificationManager;
	// 通知
	private Notification notification;

	// 上一首
	private ImageButton lastImageButton;
	// 播放
	private ImageButton playImageButton;
	// 下一首
	private ImageButton nextImageButton;
	// 循环
	private ImageButton loopImageButton;
	// 播放进度
	private SeekBar playSeekBar;
	// 当前播放曲目
	private TextView currentPlayingSong;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.listview);
		lastImageButton = (ImageButton) findViewById(R.id.imagebutton_previous);
		playImageButton = (ImageButton) findViewById(R.id.imagebutton_play);
		nextImageButton = (ImageButton) findViewById(R.id.imagebutton_next);
		loopImageButton = (ImageButton) findViewById(R.id.imagebutton_loops);
		playSeekBar = (SeekBar) findViewById(R.id.seekbar_play);
		currentPlayingSong = (TextView) findViewById(R.id.textview_songinformation);
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		list = new ArrayList<HashMap<String, String>>();

		adapter = new SimpleAdapter(this, list, R.layout.list_item,
				new String[] { "title" }, new int[] { R.id.textview_item });
		listView.setAdapter(adapter);

		// 为listView设置监听器
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				try {
					currentPositionMusic = position;
					playMusic(((HashMap<String, String>) list
							.get(currentPositionMusic)).get("path"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		lastImageButton.setOnClickListener(this);
		playImageButton.setOnClickListener(this);
		nextImageButton.setOnClickListener(this);
		loopImageButton.setOnClickListener(this);
		playSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (fromUser && mediaPlayer != null) {
					mediaPlayer.seekTo(progress);
				}
			}
		});
	}

	@Override
	protected void onStop() {
		super.onStop();
		notification = new Notification(R.drawable.app_icon, "百度音乐",
				System.currentTimeMillis());

		notification.flags |= Notification.FLAG_NO_CLEAR;
		notification.flags |= Notification.FLAG_ONGOING_EVENT;

		Intent intent = new Intent(this, this.getClass());
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				intent, 0);

		notification.setLatestEventInfo(this, "正在播放",
				((HashMap<String, String>) list.get(currentPositionMusic))
						.get("title"), pendingIntent);

		notificationManager.notify(1, notification);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 得到所有音频
		scanMusic();
		notificationManager.cancelAll();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		notificationManager.cancelAll();
		mediaPlayer.release();
		mediaPlayer = null;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("你确定要退出吗?");
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			builder.show();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	/**
	 * 得多所有的音频
	 */
	private void scanMusic() {
		new Thread() {
			public void run() {
				Cursor cursor = getContentResolver().query(
						MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
						null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

				while (cursor.moveToNext()) {
					String title = cursor
							.getString(cursor
									.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
					String path = cursor
							.getString(cursor
									.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
					String size = cursor
							.getString(cursor
									.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
					if (Long.parseLong(size) > 1024 * 1024) {
						HashMap<String, String> hashMap1 = new HashMap<String, String>();
						hashMap1.put("title", title);
						hashMap1.put("path", path);
						list.add(hashMap1);
						handler.sendEmptyMessage(LOADING_DATA);
					}
				}
				cursor.close();

			};
		}.start();

	}

	/**
	 * 播放音乐
	 * 
	 * @param path
	 * @throws Exception
	 */
	private void playMusic(String path) throws Exception {
		if (mediaPlayer == null) {
			// 新建一个mediaPalyer对象
			mediaPlayer = new MediaPlayer();
		}
		// 使mediaPalyer进入Idle状态
		mediaPlayer.reset();
		// 设置数据源,使mediaPlayer进入Intialized状态
		mediaPlayer.setDataSource(path);
		// 准备播放
		mediaPlayer.prepareAsync();
		mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {
				// 开始播放音乐
				mp.start();
				// 把图片改为播放的图片
				playImageButton.setImageResource(R.drawable.play);
				// 同时更改SeekBar的进度,因为进度是不断变化的,所以需要一个子线程来刷新下
				playSeekBar.setMax(mp.getDuration());
				handler.sendEmptyMessage(UPDATE_PROGRESS);
				// 设置当前播放曲目信息
				currentPlayingSong.setTextColor(Color.GREEN);
				currentPlayingSong.setText(list.get(currentPositionMusic).get(
						"title"));
			}
		});
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				playNextSong();
			}
		});
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_PROGRESS:
				playSeekBar.setProgress(mediaPlayer.getCurrentPosition());
				handler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 1000);
				break;
			case LOADING_DATA:
				adapter.notifyDataSetInvalidated();
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imagebutton_previous:
			playLastSong();
			break;
		case R.id.imagebutton_play:
			if (mediaPlayer != null) {
				// 如果音乐播放器正在播放
				if (mediaPlayer.isPlaying()) {
					// 那就暂停它
					mediaPlayer.pause();
					// 还要把图片改为暂停的图片
					playImageButton.setImageResource(R.drawable.pause);
				} else {
					// 否则就播放它
					mediaPlayer.start();
					// 把图片设置成播放的图片
					playImageButton.setImageResource(R.drawable.play);
				}
			}
			break;
		case R.id.imagebutton_next:
			playNextSong();
			break;
		case R.id.imagebutton_loops:
			if (mediaPlayer != null) {
				// 如果音乐播放器正在循环
				if (mediaPlayer.isLooping()) {
					// 那就终止循环它
					mediaPlayer.setLooping(false);
					// 还要把图片改为不循环的图片
					loopImageButton.setImageResource(R.drawable.loop_false);
				} else {
					// 否则就循环播放它
					mediaPlayer.setLooping(true);
					// 把图片设置成循环播放的图片
					loopImageButton.setImageResource(R.drawable.loop_true);
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 播放下一曲
	 */
	private void playNextSong() {
		// 只有当有音乐在播放的时候才可以点击下一首
		if (currentPositionMusic != -1) {
			// 如果当前歌曲为最后一首,就播放第一首歌曲
			if (currentPositionMusic == list.size() - 1) {
				// 设置当前歌曲为第一首
				currentPositionMusic = 0;
				try {
					// 播放第一首歌曲
					playMusic(list.get(currentPositionMusic).get("path"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}// 否则就播放下一首歌曲
			else {
				// 设置当前歌曲为下一首
				currentPositionMusic++;
				try {
					// 播放下一首歌曲
					playMusic(list.get(currentPositionMusic).get("path"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}

	/**
	 * 播放上一曲
	 */
	private void playLastSong() {
		// 只有当有音乐在播放的时候才可以点击上一首
		if (currentPositionMusic != -1) {
			// 如果当前歌曲为第一首,就播放最后一首歌曲
			if (currentPositionMusic == 0) {
				// 设置当前歌曲为最后一首
				currentPositionMusic = list.size() - 1;
				try {
					// 播放最后一首歌曲
					playMusic(list.get(currentPositionMusic).get("path"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}// 否则就播放上一首歌曲
			else {
				// 设置当前歌曲为前一首
				currentPositionMusic--;
				try {
					// 播放前一首歌曲
					playMusic(list.get(currentPositionMusic).get("path"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}

}

xml代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

    <LinearLayout
        android:id="@+id/linearlayout_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textview_songinformation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <ImageButton
            android:id="@+id/imagebutton_previous"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:src="@drawable/last" />

        <ImageButton
            android:id="@+id/imagebutton_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:src="@drawable/pause" />

        <ImageButton
            android:id="@+id/imagebutton_next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:src="@drawable/next" />

        <ImageButton
            android:id="@+id/imagebutton_loops"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:src="@drawable/loop_false" />
    </LinearLayout>

    <SeekBar
        android:id="@+id/seekbar_play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/linearlayout_button" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview_item"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:textColor="#a2007c" >

</TextView>

剩下的就是添加一些图片资源和在AndroidManifest.xml中添加权限和样式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值