简易音乐播放器

音乐播放器需要在后台运行,因此是通过服务实现的,在服务中设置一些方法,然后调用服务中的方法来实现的,这里也添加了一个进度条,在主Activity种刷新进度条。

原理可以参考https://blog.csdn.net/augfun/article/details/54986142

清单文件,配置一个服务

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ldw.mediaPlayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ldw.mediaPlayer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.ldw.mediaPlayer.mediaService"/>
    </application>

</manifest>

布局文件activity_main.xml配置一些按钮

<LinearLayout 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: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" 
    android:orientation="vertical"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="播放" 
        android:onClick="play"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="继续播放" 
        android:onClick="continuePlay"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="暂停" 
        android:onClick="pause"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="退出" 
        android:onClick="quit"
        />
    <SeekBar 
        android:id="@+id/sb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

MainActivity.java

package com.ldw.mediaPlayer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity {

	//定义成静态来获取mediaService的进度条
	static Handler handler = new Handler(){
		public void HandleMessage(android.os.Message msg){
			//刷新seekbar的UI
			Bundle bundle = msg.getData();
			int length = bundle.getInt("length");
			int currentLength = bundle.getInt("currentLength");
			//刷新进度条
			sb.setMax(length);
			sb.setProgress(currentLength);
		}
	};
	mediaInterface mi;
	private mediaServiceConn conn;
	private Intent intent;
	private static SeekBar sb;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //获取seekbar
        sb = (SeekBar)findViewById(R.id.sb);
        //监听seekbar,实现seekbar进度的改变
        sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				System.out.println("手指滑动");
				
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				System.out.println("手指按下");
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				System.out.println("手指抬起");
				//根据拖动进度改变进度条
				int progress = seekBar.getProgress();
				//改变进度
				mi.seekTo(progress);
				
			}
        	
        });
        intent = new Intent(this, com.ldw.mediaPlayer.mediaService.class);
        conn = new mediaServiceConn();
        //混合调用service,避免服务avtivy关闭服务就关闭了。顺序是先startService再bindService,关闭是先解绑再停止
        //把服务所在的进程变成服务进程
        startService(intent);
        //拿到中间对象
        bindService(intent, conn, BIND_AUTO_CREATE);
    }
    
    class mediaServiceConn implements ServiceConnection{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mi = (mediaInterface) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
    	
    }

    //开始播放按钮
    public void play(View v){
    	mi.play();
    }
    
    //暂停播放按钮
    public void pause(View v){
    	mi.pause();
    }
    
    //继续播放
    public void continuePlay(View v){
    	mi.continuePlay();
    }
    
    //退出
    public void quit(View v){
    	unbindService(conn);
    	stopService(intent);
    }
    
}

定义一个音乐播放器的服务mediaService.java

package com.ldw.mediaPlayer;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

public class mediaService extends Service {

	MediaPlayer player;
	private Timer timer;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return new zhongjian();
	}
	
	@Override
	public void onCreate(){
		super.onCreate();
		player = new MediaPlayer();
	}
	
	//停止播放在服务销毁的时候调用
	@Override
	public void onDestroy(){
		super.onDestroy();
		//关闭播放器
		player.stop();
		//释放资源,释放掉player对象
		player.release();
		player = null;
		//停掉计时器
		if(timer != null){
			timer.cancel();
			timer = null;
		}
	}
	
	//必须继承binder才能作为中间对象被返回
	class zhongjian extends Binder implements mediaInterface{
		public void play(){
			mediaService.this.play();
		}
		public void pause(){
			mediaService.this.pause();
		}
		@Override
		public void continuePlay() {
			// TODO Auto-generated method stub
			mediaService.this.continuePlay();
			
		}
		@Override
		public void seekTo(int progress) {
			// TODO Auto-generated method stub
			mediaService.this.seekTo(progress);
		}
	}
	
	//播放音乐
    public void play(){
    	//重置
    	player.reset();
    	try {
			//player.setDataSource("sdcard/1.mp3");
			//设置加载网络资源
			player.setDataSource("sdcard/1.mp3");
			//异步准备
			player.prepareAsync();
			//准备侦听,开始播放
			player.setOnPreparedListener(new OnPreparedListener(){

				@Override
				public void onPrepared(MediaPlayer mp) {
					// TODO Auto-generated method stub
					player.start();
					addTimer();
				}
				
			});
	    	//player.prepare();
	    	//player.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    //暂停播放
    public void pause(){
    	player.pause();
    }
    
    //继续播放
    public void continuePlay(){
    	player.start();
    }
    
    //改变当前的进度
    public void seekTo(int process){
    	player.seekTo(process);
    }
    
    public void addTimer(){
    	//计时器Timer,第二个参数是延迟,指代码执行以后5ms以后第一次执行run方法,以后每
    	//500ms执行一次。最后一个参数是执行run方法的间隔时间500,
    	if(timer == null){
	    	timer = new Timer();
	    	timer.schedule(new TimerTask(){
	
				@Override
				public void run() {
					// TODO Auto-generated method stub
			    	//获取歌曲的时长,单位是毫秒
			    	int length = player.getDuration();
			    	//获取歌曲当前的播放进度
			    	int currentLength = player.getCurrentPosition();
			    	
			    	//想MainActivity发消息携带数据
			    	Message msg = MainActivity.handler.obtainMessage();
			    	//把进度封装到对象中
			    	Bundle bundle = new Bundle();
			    	bundle.putInt("length", length);
			    	bundle.putInt("currentLength", currentLength);
			    	msg.setData(bundle);
			    	//发送到主线程
			    	MainActivity.handler.sendMessage(msg);
				}
	    		
	    	}, 5, 500);
    	}
    }

}

定义一个接口mediaInterface.java来规范服务中的方法:

package com.ldw.mediaPlayer;

public interface mediaInterface {
	void play();
	void pause();
	void continuePlay();
	void seekTo(int progress);
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值