找传奇、传世资源到传世资源站!

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

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

android音乐播放器_源码下载(可扫描本地歌曲)_ Android平台开发-第1张

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);
	}
  
}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复