Android之播放一首简单的音乐

1.首先,创建一个项目,名为Mp3Test,创建完之后打开res目录下的layout下的activity_main.xml文件,打开src下的MainActivity.java文件,首先,先把布局文件写好,布局文件activity_main.xml文件下有个TextView控件和4个Button控件,我还在drawable-hdpi文件夹下放置了background.png背景图片,接下来附上布局文件代码:

<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:orientation="vertical"
    android:background="@drawable/background" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="播放一首简单的音乐"
        android:textSize="20sp"
        android:gravity="center_horizontal|center_vertical"/>
    
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
        
    <Button
        android:id="@+id/play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="播放"
        android:onClick="click" 
        android:padding="20dp"/>

    <Button
        android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="暂停" 
        android:onClick="click"
        android:padding="20dp" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止"
        android:onClick="click"
        android:padding="20dp"  />

    <Button
        android:id="@+id/exit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:padding="20dp"
        android:text="退出" />
    
    </LinearLayout>

</LinearLayout>

2.接下来要创建多一个类,继承于Service类,那个类我创建时取为ServiceTest类,下面先附上MainActivity.java文件的代码,这里用来显示界面和用Intent对象作为桥梁,把播放,暂停,停止音乐播放放在后台来进行,ServiceTest.java文件用来后台服务:

MainActivity.java文件:

package com.example.mp3test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	public void click(View v){
		Intent intent=new Intent(MainActivity.this, ServiceTest.class);
		int op=-1;//一个中间变量
		//获得各自的按钮控件
		switch (v.getId()) {
		case R.id.play://播放按钮
			op=1;
			break;
		case R.id.pause://暂停按钮
			op=2;
			break;
		case R.id.stop://停止按钮
			op=3;
			break;
		case R.id.exit://退出按钮
			stopService(intent);//停止服务
			finish();//退出本界面
			break;
		default:
			break;
		}
		Bundle bundle=new Bundle();
		bundle.putInt("msg", op);
		intent.putExtras(bundle);
		startService(intent);//开始服务
	}
}

接下里附上ServiceTest.java文件,用来处理后台服务的事情,在这里我们把我们所需要的资源放进去,在res目录下创建一个新的文件夹raw,把一个音乐文件复制进去,注意音乐文件命名要合法,不能有中文,还必须全部小写,我们就把jasmine.mp3复制进去:

ServiceTest.java:

 

package com.example.mp3test;

import java.io.IOException;

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

public class ServiceTest extends Service {
	
	private MediaPlayer player;// 创建player对象
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	//服务创建
	@Override
	public void onCreate() {
		if(player==null){
		player=player.create(ServiceTest.this, R.raw.jasmine);//设置音乐资源并实例化player
		player.setLooping(false);//音乐不能循环
		super.onCreate();
		}
	}

	//服务销毁
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		player.release();//释放资源
		super.onDestroy();
	}

	//服务开始
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Bundle bundle=intent.getExtras();
		int op=bundle.getInt("msg");//获得从MainActivity.java里传递过来的op
		switch (op) {
		case 1://当op为1,即点击了播放按钮
			play();//调用play()方法
			break;
		case 2://当op为2,即点击了暂停按钮
			pause();//调用pause()方法
			break;
		case 3://当op为3,即点击了停止按钮
			stop();//调用stop()方法
			break;
		default:
			break;
		}
		return super.onStartCommand(intent, flags, startId);
	}

	private void stop() {
		// TODO Auto-generated method stub
		if(player.isPlaying()){
			player.stop();//停止播放音乐
			try {
				player.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void pause() {
		// TODO Auto-generated method stub
		if(player.isPlaying()&&player!=null){
			player.pause();//暂停播放音乐
		}
	}

	private void play() {
		// TODO Auto-generated method stub
		if(!player.isPlaying()){
			player.start();//开始播放音乐
		}
	}
	
	

}


3.接下来别忘了一点,就是你写的那个继承于Service类的ServiceTest必须在AndroidManifest.xml文件里声明一个service,即加上这条代码:

  <service android:name=".ServiceTest"></service>

AndroidManifest.xml文件:

 

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mp3test.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=".ServiceTest"></service>
    </application>

</manifest>


4.代码已经完成,接下来开始运行这个安卓项目,运行效果如下图所示:


点击播放按钮,开始播放那首我放入的mp3音乐,点击暂停按钮正在播放的音乐被停止了,点击播放音乐又继续播放,点击停止按钮,将停止音乐的播放,释放音乐资源,点击播放又将开始从头播放,如果你点击虚拟机的那个返回虚拟键盘键,音乐还是在后台播放,点击退出按钮,后台音乐停止播放,退出本界面。

5.以上的内容,是我学习积累所得,如有雷同,纯属巧合,仅供大家学习参考,写得不好,请见谅,如有什么错误请指出,谢谢!



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值