Android游戏开发学习笔记(二):音频的播放
	android中有两种方式可以播放音频,一种是SoundPool,一种是MediaPlayer。前者适合短促但对反应速度要求较高的情况(如游戏中的爆炸声),后者适合较长当对时间要求不高的情况(如游戏中的背景音乐)。示例如下:
	首先,创建项目Sound,在res下新建目录raw用于存放声音文件,讲需要的声音文件放入该目录。
	然后编写布局文件main.xml,代码如下:
	<?xml version="1.0" encoding="utf-8"?>
	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	    android:orientation="vertical"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	    >
	<TextView  
	    android:id="@+id/textView"  
	    android:layout_width="fill_parent"  
	    android:layout_height="wrap_content"  
	    android:text="没有播放任何声音"
	    />
	<Button
	    android:id="@+id/btn1"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="使用MediaPlayer播放声音"  
	    />
	<Button
	    android:id="@+id/btn2"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="暂停MediaPlayer声音"  
	    />
	<Button
	    android:id="@+id/btn3"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="使用SoundPool播放声音"  
	    />
	<Button
	    android:id="@+id/btn4"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="暂停SoundPool声音"  
	    />
	</LinearLayout>
	最后,在MainActivity.java中编写代码,根据不同的按钮事件执行播放和暂停的操作。代码如下:
	package game.test; 
	 
	import java.util.HashMap; 
	import android.app.Activity; 
	import android.content.Context; 
	import android.media.AudioManager; 
	import android.media.MediaPlayer; 
	import android.media.SoundPool; 
	import android.os.Bundle; 
	import android.view.View; 
	import android.view.View.OnClickListener; 
	import android.widget.Button; 
	
相关新闻>>
- 发表评论
- 
				
- 最新评论 进入详细评论页>>





