Android之简易音乐播发器

原创 2015年11月17日 20:36:06

布局主要代码之ListView:

<span style="font-size:14px;"> <ListView
        android:id="@+id/music_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/handle_btnlayout"
        android:cacheColorHint="#00000000"      /*设置为透明,防止滑动时背景变成白色*/
        android:dividerHeight="1dip"
        android:divider="#88888888"          /*设置分割线的颜色和透明度*/
        android:listSelector="#00000000"
        android:layout_marginBottom="50dp" >
 </ListView></span>

Android之UI界面代码:

<span style="font-size:14px;">public class Music extends BaseActivity{       //BaseActivity继承Activity作为所有活动的父类
	public static final String ACTION_UPDATEUI = "action.updateUI";
	private ListView ls = null;
	private Button play_music = null;
	private Button previous_music =null;
	private Button next_music =null;
	private Button repeat_music = null;
	private Button shuffle_music =null;
	private TextView music_title = null;
	private TextView music_duration =null;
	public static List<Map<String, String>> list ;
	private Boolean start = false;
	private Boolean isrepeat = MusicService.repeat;
	UpdateUIBroadcastReceiver broadcastReceiver;
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.home_activity_layout);
		play_music = (Button) findViewById(R.id.play_music);
		previous_music = (Button) findViewById(R.id.previous_music);
		next_music = (Button) findViewById(R.id.next_music);
		repeat_music = (Button) findViewById(R.id.repeat_music);
		shuffle_music = (Button) findViewById(R.id.shuffle_music);
		music_title = (TextView) findViewById(R.id.music_title);
		music_duration = (TextView) findViewById(R.id.music_duration);
		music_title.setText(MusicService.music_title);
		music_duration.setText(MusicService.music_time);
		
		play_music.setOnClickListener(new ButtonsetOnClickListener());
		previous_music.setOnClickListener(new ButtonsetOnClickListener());
		next_music.setOnClickListener(new ButtonsetOnClickListener());
		repeat_music.setOnClickListener(new ButtonsetOnClickListener());
		shuffle_music.setOnClickListener(new ButtonsetOnClickListener());
		if(MusicService.isplay){
			play_music.setBackgroundResource(R.drawable.pause_selector);
		}else{
			play_music.setBackgroundResource(R.drawable.play_selector);
		}
		if(isrepeat){
			repeat_music.setBackgroundResource(R.drawable.repeat_all_selector);
		}else{
			shuffle_music.setBackgroundResource(R.drawable.shuffle_selector);
		}
		//动态注册广播接收器
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_UPDATEUI);
		broadcastReceiver = new UpdateUIBroadcastReceiver();
		registerReceiver(broadcastReceiver, filter);
		
		ls = (ListView) findViewById(R.id.music_list);
		//接下来要将这些数据封装成ArrayAdapter对象
		SimpleAdapter adapter = this.getAdapter();
		ls.setAdapter(adapter);
		ls.setOnItemClickListener(new ItemClick());     //点击
		ls.setOnItemLongClickListener(null);   //长按
		ls.setOnItemSelectedListener(null);    //勾选
	}
	private class ButtonsetOnClickListener implements OnClickListener{
		Intent intent =new Intent(Music.this, MusicService.class);           //记得注册Service
		Bundle bundle = new Bundle();
		@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.play_music:
				if(start){
					play_music.setBackgroundResource(R.drawable.play_selector);
					bundle.putBoolean("start", false);
					start = false;
				}else{
					play_music.setBackgroundResource(R.drawable.pause_selector);
					bundle.putBoolean("start", true);
					start = true;
				}
				break;
			case R.id.previous_music:
				bundle.putBoolean("previous", true);
				break;
			case R.id.next_music:
				bundle.putBoolean("next", true);
				break;
			case R.id.repeat_music:
				bundle.putBoolean("repeat", true);
				repeat_music.setBackgroundResource(R.drawable.repeat_all_selector);
				shuffle_music.setBackgroundResource(R.drawable.shuffle_none_selector);
				break;
			case R.id.shuffle_music:
				bundle.putBoolean("shuffle", true);
				shuffle_music.setBackgroundResource(R.drawable.shuffle_selector);
				repeat_music.setBackgroundResource(R.drawable.repeat_none_selector);
				break;
				default:
				break;
			}
			intent.putExtras(bundle); 		//Intent传递参数
			Music.this.startService(intent);    //启动服务
		}
	}
	//定义广播接收器(内部类)
	private class UpdateUIBroadcastReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			music_title.setText(String.valueOf(intent.getExtras().getString("music_title")));
			music_duration.setText(String.valueOf(intent.getExtras().getString("music_time")));
		}
	}
	@SuppressLint("SimpleDateFormat")
	private SimpleAdapter getAdapter(){
		// 使用SimpleAdapter来封装数据时必需要把每个显示的数据封装成Map
		list=new ArrayList<Map<String, String>>();
		SimpleDateFormat format = new SimpleDateFormat("mm:ss");
		//取得所有在外部存储卡上的音乐文件的信息 ps : MediaStore.Audio.Media.INTERNAL_CONTENT_URI 获得内置存储 
		Cursor cursor = Music.this.getContentResolver().query(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, 
				MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
		cursor.moveToFirst();
		for(int i=0;i<cursor.getCount();i++){
			String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));   //歌曲的名称
			String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));   //歌曲文件的路径
			int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));	 //歌曲的总播放时长
			String hmsString = format.format(duration);
			Map<String, String>map =new HashMap<String, String>(); 
			map.put("title", title);         
			map.put("time", hmsString);
			map.put("url", url);
			list.add(map);
			cursor.moveToNext();
		}
		SimpleAdapter adapter =new SimpleAdapter(this,               //上下文,显示对象
				list,                                                 // 要显示的数据,一定要上面的格式进行封装
				R.layout.music_list,                   // 列表中要显示的单项信息的布局
				new String[]{"title","time"},    // map中的key
				new int[]{R.id.music_title_my,R.id.music_time_my});    // 显示到组件
		
		return adapter;
	}
	//点击事件
	private class ItemClick implements OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent =new Intent(Music.this, MusicService.class);           //记得注册Activity
			Bundle bundle = new Bundle();
			bundle.putBoolean("playing", true);
			bundle.putInt("position", position);
			intent.putExtras(bundle); 		//Intent传递参数
			Music.this.startService(intent);    //启动服务
			play_music.setBackgroundResource(R.drawable.pause_selector);
		}
	}
}
</span>


<span style="font-size:14px;">public class MusicService extends Service{
	public static String music_title ="";
	public static String music_time ="";
	private MediaPlayer mp ;
	private List<Map<String, String>> list = Music.list;
	private int position ;
	private boolean playing = false;
	private boolean start = true;
	private boolean previous = false;
	private boolean next =false;
	public static boolean repeat = true;
	private boolean shuffle = false;
	public static boolean isplay = false;
	Random random = new Random();
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	@Override
	public void onCreate(){
		super.onCreate();
		/*
		final Intent intent = new Intent();
		intent.setAction(Music.ACTION_UPDATEUI);
		timer = new Timer();
		task = new TimerTask() {
			@Override
			public void run() {
				intent.putExtra("count", ++count);
				sendBroadcast(intent);
			}
		};
		timer.schedule(task, 1000,1000);
		*/
	}
	@SuppressLint("NewApi")
	@Override
	public int onStartCommand(Intent intent, int flags, int startId){
		start = intent.getBooleanExtra("start", true);       //取不到值,默认false
		playing = intent.getBooleanExtra("playing", false);
		previous = intent.getBooleanExtra("previous", false);
		next = intent.getBooleanExtra("next", false);
		if(repeat){
			shuffle = intent.getBooleanExtra("shuffle", false);
			if(shuffle){
				repeat = false;
			}
		}else if(shuffle){
			repeat = intent.getBooleanExtra("repeat", false);
			if(repeat){
				shuffle = false;
			}
		}
		if(playing){
			position = intent.getIntExtra("position",1);
			Uri uri = Uri.parse(list.get(position).get("url"));
			playsong(uri);
		}else if(previous){
			previoussong();
		}else if(next){
			nextsong();
		}
		if(mp!=null){
			if(start){
				mp.start();
				isplay = true;
			}else{
				mp.pause();   //暂停播放
				isplay = false;
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}
	private void playsong(Uri uri){
		if(mp!=null&&mp.isPlaying()){
			mp.stop();    //停止播放
		}
		mp = MediaPlayer.create(this, uri);
		mp.start();
		mp.setOnCompletionListener(new CompletionListener());
		music_title = list.get(position).get("title");
		music_time = list.get(position).get("time");
		//发送广播,改变界面
		Intent intent = new Intent();
		intent.setAction(Music.ACTION_UPDATEUI);
		Bundle bundle = new Bundle();
		bundle.putString("music_title",music_title) ;
		bundle.putString("music_time", music_time);
		intent.putExtras(bundle);
		sendBroadcast(intent);
	}
	//获取随机数
	private int randomInt(){
		int num = random.nextInt(list.size());
		if(num>=1&&num<=list.size()-1){
			return num;
		}else{
			return randomInt();
		}
	}
	private void previoussong(){
		if(repeat){
			position--;
			if(position<=1){
				position = list.size()-1;
			}
		}else{
			position = randomInt();
		}
		String urlstr = list.get(position).get("url");
		Uri uri = Uri.parse(urlstr);
		playsong(uri);
	}
	private void nextsong(){
		if(repeat){
			position++;
			if(position>=list.size()){
				position = 1;
			}
		}else{
			position = randomInt();
		}
		String urlstr = list.get(position).get("url");
		Uri uri = Uri.parse(urlstr);
		playsong(uri);
	}
	private class CompletionListener implements OnCompletionListener{
		@Override
		public void onCompletion(MediaPlayer mp) {
			nextsong();
		}
	}
	@Override
	public void onDestroy(){
		super.onDestroy();
		if(mp!=null) mp.release();   //释放资源
		stopSelf();
	//	timer.cancel();
	}
}</span>


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Android 简易音乐动态相册(多种动画)

需要完成效果:点击空白处,音乐与图片同时开始播放,音乐暂停时,图片停止播放。 布局: <RelativeLayout xmlns:android="http://schemas.android.co...

Android 使用Service 实现的简易音乐播放器(有播放、暂停(继续)、重播、停止)

小弟乃Android新手,昨天在学习了Android的Service后,动手实现了一个简易的音乐播放器。界面粗糙,功能简陋,但觉得对于新手的话还是有一定的借鉴作用的,故发表在本人的第一篇博客中。 在...

android之service音乐简易版播放器

回应需求,故做了一个简易版的使用service的音乐播放器。这个音乐播放器支持暂停,停止,开始,前一首,后一首这5个功能。    实现这个播放器主要需要用到三个类,一个是Activtiy,一个是se...

Android——简易音乐播放器

通过服务实现简易的音乐播放器 mediaplayer的基本使用方法

android----极其简易的音乐播放器(service的使用)

俱乐部的作业已经拖了一周了,实在不好意思再不弄了。。。前天晚上开了个头,总是因为资源太大运行不了,导致一直没法继续编下去。。今天偶然发现居然删掉了之前工程里的音乐资源就又能加进去一个音乐了~为了避免再...

Android 简易的音乐播放器

Android 简易的音乐播放器MediaPlayer

Android之简易的音乐播放器

1.播放项目内的音乐 package com.thm.g150820_android26_playmusic; import android.media.MediaPlayer; import ...

Android的简易音乐播放器

这些日子都在学习Android的应用开发,于是参考了Android从入门到精通里的代码(明日科技),抄抄写写做了一个简易的音乐播放器,修修改改也看了好多网上的代码,在三星盖世3上测试可以运行(关闭时会...

Android开发笔记之简易音乐播放器

今天做了一个简易的音乐播放器程序,其实主要是运用一下MediaPlayer。 播放器有两个按钮,分别是播放和暂停;一个textview显示文件总时长;两个seekbar,分别是调节进度和音量大小。 ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)