在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Android平台开发 → android音乐播放器 源码下载(可扫描本地歌曲)

android音乐播放器 源码下载(可扫描本地歌曲)

Android平台开发

下载此实例
  • 开发语言:Java
  • 实例大小:1.61M
  • 下载次数:81
  • 浏览次数:626
  • 发布时间:2016-12-25
  • 实例类别:Android平台开发
  • 发 布 人:herui
  • 文件格式:.zip
  • 所需积分:2
 相关标签: android音乐播放器

实例介绍

【实例简介】

【实例截图】

【核心代码】

package com.example.audioplayer;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import com.example.audioplayer.MusicListAdapter.OnItemClickListener;
import com.example.autioplayer.R;

import android.R.integer;
import android.R.string;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.Intent;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.app.TaskStackBuilderHoneycomb;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class PlayerActivity extends Activity {
	private static Intent startIntent;
	private int playState;
	private SeekBar seekBar;
	private TextView text_prompt;
	private TextView text_listnfo;
	private TextView text_sonName;
	private TextView text_currentTime;
	private TextView text_seekTime;
	private TextView text_duration;
	private ImageView image_setloopMode;
	private MusicListAdapter musicListAdapter;
	private int current_id;
	private int currentTime;
	private int duration;
	private int playMode = 3;			//播放状态,默认为顺序播放
	private boolean canSeek = true;
	private Toast mToast;
	private List<AudioInfo> audioList;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        initialize();
    }


    private void initialize() {
    	
    	initializeBroadcast();
		initializeView();
		
		if(startIntent == null)
		{
			startIntent = new Intent();
			startIntent.setAction("com.example.audioplayer.PLAYER_SERVICE");
			startService(startIntent);
		}
	}
    
    private void initializeView() {
    	findViewById(R.id.imageView_btn_play_or_pause).setOnClickListener(new ButtonClick());
		findViewById(R.id.imageView_btn_stop).setOnClickListener(new ButtonClick());
		findViewById(R.id.imageView_btn_back_last).setOnClickListener(new ButtonClick());
		findViewById(R.id.imageView_btn_forward_next).setOnClickListener(new ButtonClick());
		text_prompt = (TextView)findViewById(R.id.text_prompt);
		text_listnfo = (TextView)findViewById(R.id.text_list_info);
		text_sonName = (TextView)findViewById(R.id.text_song_name);
		text_currentTime = (TextView)findViewById(R.id.text_current_time);
		text_duration = (TextView)findViewById(R.id.text_duration);
		text_seekTime = (TextView)findViewById(R.id.text_seekTime);
		image_setloopMode = (ImageView)findViewById(R.id.image_setloopMode);
		image_setloopMode.setOnClickListener(new ButtonClick());
		setPlayMode(playMode);
		seekBar = (SeekBar) findViewById(R.id.seekBar);
		seekBar.setOnSeekBarChangeListener(new ChangeListener());
		ListView musicList = (ListView)findViewById(R.id.musiic_list);
		audioList = AudioFileService.getAudioInfolist(getApplicationContext());
		musicListAdapter = new MusicListAdapter(getApplicationContext(), audioList);
		musicList.setAdapter(musicListAdapter);
		musicListAdapter.SetOnListItemClickListener(new OnItemClickListener(){

			@Override
			public void OnClick(int position) {
				// TODO Auto-generated method stub
				Intent controlIntent = new Intent();
				controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
				controlIntent.putExtra("control", AppConstant.PlayerMsg.PLAY_LIST_BY_POS);
				controlIntent.putExtra("position", position);
				//发送普通广播
				sendBroadcast(controlIntent);
			}
			
		});
	}


	public String getAudioName(int index){
    	if(index >= 0 && index < audioList.size()){
    		String fileName = audioList.get(index).getName();
    		return fileName.substring(0, fileName.lastIndexOf('.'));
    	}
    	return "";
    };


	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_rescan) {
        	Intent controlIntent = new Intent();
			controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
			controlIntent.putExtra("control", AppConstant.PlayerMsg.REQUEST_RELOAD);
			sendBroadcast(controlIntent);
            return true;
        }
        
        if (id == R.id.action_exit) {
        	stopPlayerService();
        	finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            quit();
        }
        return false;
    }
    
    public void quit(){
    	// 创建退出对话框
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(
                this);
        // 设置对话框标题
        dialogBuilder.setTitle("提示");
        // 设置对话框消息
        dialogBuilder.setMessage("确定要退出吗?");
        // 添加选择按钮并注册监听
        dialogBuilder.setNeutralButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                    	stopPlayerService();
                        finish();
                    }
                });
        dialogBuilder.setNegativeButton("取消", null);
        // 显示对话框
        dialogBuilder.create().show();
    }
    
    protected void stopPlayerService() {
    	Intent controlIntent = new Intent();
    	controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
		controlIntent.putExtra("control", AppConstant.PlayerMsg.STOP_MSG);
		new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(startIntent != null)
				{
					startIntent = new Intent();
					startIntent.setAction("com.example.audioplayer.PLAYER_SERVICE");
					stopService(startIntent);
					startIntent = null;
				}
				
			}
		}, 500);
    	
	}
    
    public void setButtonIcon(int playSate) {
		ImageView imageView = (ImageView)findViewById(R.id.imageView_btn_play_or_pause);
		if(playSate == AppConstant.PlayState.PLAYING)
			imageView.setImageResource(R.drawable.btn_pause);
		else
			imageView.setImageResource(R.drawable.btn_play);
	}
    
    public void setPlayMode(int playMode) {
    	Intent controlIntent = new Intent();
		controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
		controlIntent.putExtra("control", AppConstant.PlayerMsg.PLAY_MODE_CHANGE);
		controlIntent.putExtra("palayMode", playMode);
		sendBroadcast(controlIntent);
		int ids[] = {R.drawable.image_songlop_play, R.drawable.image_listloop_play,
				R.drawable.image_order_play, R.drawable.image_random_play};
		String prompts[] = {"单曲循环", "列表循环", "顺序播放", "随机播放"};
		showToast(prompts[playMode-1]);
		image_setloopMode.setImageResource(ids[playMode-1]);
	}

	class ButtonClick implements android.view.View.OnClickListener{

		@Override
		public void onClick(View v) {
			Intent controlIntent = new Intent();
			switch (v.getId()) {
			case R.id.imageView_btn_play_or_pause:
				//设置Intent的Action属性
				controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
				controlIntent.putExtra("control", AppConstant.PlayerMsg.PLAY_MSG);
				break;
			case R.id.imageView_btn_stop:
				//设置Intent的Action属性
				controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
				controlIntent.putExtra("control", AppConstant.PlayerMsg.STOP_MSG);
				
				break;
			case R.id.imageView_btn_back_last:
				//设置Intent的Action属性
				controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
				controlIntent.putExtra("control", AppConstant.PlayerMsg.PRIVIOUS_MSG);
				break;
			case R.id.imageView_btn_forward_next:
				//设置Intent的Action属性
				controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
				controlIntent.putExtra("control", AppConstant.PlayerMsg.NEXT_MSG);
				break;
			case R.id.image_setloopMode:
				  playMode;
				if(playMode > 4)
					playMode = 1;
				setPlayMode(playMode);
				break;
			default:
				break;
			}
			//发送普通广播
			sendBroadcast(controlIntent);
		}
    	
    }
	
	
	public void initializeBroadcast(){
		BroadcastReceiver updateReceiver = new BroadcastReceiver() {
			Handler handler;
			Runnable runnable;
			@Override
			public void onReceive(Context context, Intent intent) {
				playState = intent.getIntExtra("playState", 0);
				current_id = intent.getIntExtra("MUSIC_ID", 0);
				setButtonIcon(playState);				
				int listSize = 0;
				if(audioList != null)
					listSize = audioList.size();
				text_listnfo.setText((listSize > 0?current_id 1:0) " / " listSize);
				text_sonName.setText(getAudioName(current_id));
				if(listSize == 0){
					text_currentTime.setText("00:00");
					text_duration.setText("00:00");
				}
				
				if(intent.getBooleanExtra("loading", false)){
					text_prompt.setText("正在扫描本地音乐,已经找到" listSize "首歌曲");
					musicListAdapter.notifyDataSetChanged();
					System.out.println("---------------------------------");
				}
				else if(intent.getBooleanExtra("loaded", false)){
					text_prompt.setText("共找到" listSize "首音乐");
					if(handler != null){
						handler.removeCallbacks(runnable);  
					}
					colsePrompt();
				}
			}
			
			protected void colsePrompt() {
				handler = new Handler();
				runnable = new Runnable(){
				     public void run() {
				    	 text_prompt.setText("");
				     }
				};
				handler.postDelayed(runnable, 3000);
			}
		};
		registerBoradcastReceiver(updateReceiver, AppConstant.BroadcastAction.UPDATE_ACTION);
		
		BroadcastReceiver musicCurrentReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				currentTime = intent.getIntExtra("currentTime", 0);
				if(duration > 0 && canSeek)
					seekBar.setProgress((int)(100.0f * currentTime / duration));
				text_currentTime.setText(getTimeString(currentTime));
			}
		};
		registerBoradcastReceiver(musicCurrentReceiver, AppConstant.BroadcastAction.MUSIC_CURRENT_TIME);
		
		BroadcastReceiver musicDurationReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				duration = intent.getIntExtra("duration", 0);
				text_duration.setText(getTimeString(duration));
			}
		};
		registerBoradcastReceiver(musicDurationReceiver, AppConstant.BroadcastAction.MUSIC_DURATION);
	}


	public void registerBoradcastReceiver(BroadcastReceiver mBroadcastReceiver, String ACTION_NAME){  
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTION_NAME);
        //注册广播 
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
	
	class ChangeListener implements OnSeekBarChangeListener {
		int time;
        /**
         * 拖动条停止拖动的时候调用
         */
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        	text_seekTime.setText("");
        	currentTime = this.time;
        	setPlaySeek(currentTime);
        	canSeek = true;
        }

        /**
         * 拖动条开始拖动的时候调用
         */
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        	canSeek = false;
        }

        /**
         * 拖动条进度改变的时候调用
         */
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        	if(!canSeek) {
	        	this.time = (int)(progress / 100.0f * duration);
	        	text_seekTime.setText(getTimeString(this.time));
        	}
        }
    }


	public void setPlaySeek(int seek) {
		Intent controlIntent = new Intent();
		controlIntent.setAction(AppConstant.BroadcastAction.CTL_ACTION);
		controlIntent.putExtra("control", AppConstant.PlayerMsg.PROGRESS_CHANGE);
		controlIntent.putExtra("progress", seek);
		sendBroadcast(controlIntent);
	};
	
	/**
	 * 显示Toast
	 */
	private void showToast(String msg){
        if(mToast == null){
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        }else{
            mToast.setText(msg);
        }
        mToast.show();
    }
	
	private String getTimeString(int time_ms) {
		time_ms = time_ms / 1000;
		return String.format("%02d:%02d", time_ms / 60, time_ms % 60);
	}
    
}

实例下载地址

android音乐播放器 源码下载(可扫描本地歌曲)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警