android SoundPool播放音效(二)

之前只知道android中可以用mediaplayer播放音乐,原来今天才发现 
可以用soundpool,用soundpool可以播一些短的反应速度要求高的声音, 
比如游戏中的爆破声,而mediaplayer适合播放长点的。 
1. SoundPool载入音乐文件使用了独立的线程,不会阻塞UI主线程的操作。但是这里如果音效文件过大没有载入完成,我们调用play方法时可能产生严重的后果,这里Android SDK提供了一个SoundPool.OnLoadCompleteListener类来帮助我们了解媒体文件是否载入完成,我们重载 onLoadComplete(SoundPool soundPool, int sampleId, int status) 方法即可获得。 
2. 从上面的onLoadComplete方法可以看出该类有很多参数,比如类似id,是的SoundPool在load时可以处理多个媒体一次初始化并放入内存中,这里效率比MediaPlayer高了很多。 
3. SoundPool类支持同时播放多个音效,这对于游戏来说是十分必要的,而MediaPlayer类是同步执行的只能一个文件一个文件的播放。 

使用方法: 
1. 创建一个SoundPool 

  public SoundPool(int maxStream, int streamType, int srcQuality) 

  maxStream —— 同时播放的流的最大数量 

  streamType —— 流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出) 

  srcQuality —— 采样率转化质量,当前无效果,使用0作为默认值 

  SoundPool soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); 

  创建了一个最多支持3个流同时播放的,类型标记为音乐的SoundPool。 


2 一般把多个声音放到HashMap中去,比如 
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); 
    soundPoolMap = new HashMap<Integer, Integer>();   
    soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong, 1)); 

  soundpool的加载: 
  int  load(Context context, int resId, int priority)  //从APK资源载入 
  int  load(FileDescriptor fd, long offset, long length, int priority)  //从FileDescriptor对象载入 
  int  load(AssetFileDescriptor afd, int priority)  //从Asset对象载入 
  int  load(String path, int priority)  //从完整文件路径名载入 
最后一个参数为优先级。 

3 播放 
play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) ,其中leftVolume和rightVolume表示左右音量,priority表示优先级,loop表示循环次数,rate表示速率,如 
//速率最低0.5最高为2,1代表正常速度 
sp.play(soundId, 1, 1, 0, 0, 1); 

  而停止则可以使用 pause(int streamID) 方法,这里的streamID和soundID均在构造SoundPool类的第一个参数中指明了总数量,而id从0开始。

下面给出一个例子:

package com.z.soundpooldemo;

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;

/**
 * 使用 SoundPool 播放音效,SoundPool 还支持自行设置声音的品质、音量、 播放比率等参数
 */
public class MainActivity extends Activity {

	private Button btn_player;
	private Button btn_player2;
	private Button btn_player3;
	private HashMap<Integer, Integer> musicId = new HashMap<Integer, Integer>();
	// 创建一个 SoundPool 对象
	private SoundPool soundPool;
	private MediaPlayer mediaPlayer;
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		init();

	}

	private void init() {

		//  maxStream —— 同时播放的流的最大数量 <br>
		//  streamType ——流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出)<br>
		//  srcQuality —— 采样率转化质量,当前无效果,使用0作为默认值
		soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
		// 通过load方法加载指定音频流,并将返回的音频ID放入musicId中
		musicId.put(1, soundPool.load(this, R.raw.kawayi, 1));
		musicId.put(2, soundPool.load(this, R.raw.happened, 1));
		musicId.put(3, soundPool.load(this, R.raw.happened, 1));

		btn_player = (Button) findViewById(R.id.btn_player);
		btn_player.setOnClickListener(new PlayerOnClickListener());
		btn_player2 = (Button) findViewById(R.id.btn_player2);
		btn_player2.setOnClickListener(new PlayerOnClickListener());
		btn_player3 = (Button) findViewById(R.id.btn_player3);
		btn_player3.setOnClickListener(new PlayerOnClickListener());
	}

	private class PlayerOnClickListener implements OnClickListener {

		@SuppressWarnings("static-access")
		@Override
		public void onClick(View v) {
			AudioManager am = (AudioManager) getSystemService(context.AUDIO_SERVICE);// 实例化
			float audioMaxVolum = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);// 音效最大值
			float audioCurrentVolum = am.getStreamVolume(AudioManager.STREAM_MUSIC);
			float audioRatio = audioCurrentVolum / audioMaxVolum;
			switch (v.getId()) {
			case R.id.btn_player:

				// soundID:第一个参数指定播放哪个声音;
				// leftVolume 、 rightVolume: 指定左、右的音量
				// priority:指定播放声音的优先级,数值越大,优先级越高;
				// loop:指定是否循环, 0 为不循环, -1 为循环;
				// rate:指定播放的比率,数值可从 0.5 到 2 , 1 为正常比率。
				soundPool.play(musicId.get(1), audioRatio, audioRatio, 0, 0, 1);// 播一段就停止了...
				break;
			case R.id.btn_player2:

				// soundID:第一个参数指定播放哪个声音;
				// leftVolume 、 rightVolume: 指定左、右的音量
				// priority:指定播放声音的优先级,数值越大,优先级越高;
				// loop:指定是否循环, 0 为不循环, -1 为循环;
				// rate:指定播放的比率,数值可从 0.5 到 2 , 1 为正常比率。
				soundPool.play(musicId.get(1), audioRatio, audioRatio, 0, 0, 1);// 播一段就停止了...
				break;
			case R.id.btn_player3:
				mediaPlayer = MediaPlayer.create(context, R.raw.kawayi);
				try {
					// 在播放之前先判断playerMusic是否被占用
					if (mediaPlayer != null) {
						mediaPlayer.stop();
					}
					mediaPlayer.prepare();
				} catch (Exception e) {
					e.printStackTrace();
				}
				mediaPlayer.start();
				break;

			default:
				break;
			}

		}
	}

	@Override
	protected void onDestroy() {
		soundPool.release();
		super.onDestroy();
	}
}

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="SoundPool测试" />

    <Button
        android:id="@+id/btn_player"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="播放" />

    <Button
        android:id="@+id/btn_player2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="播放2" />

    <Button
        android:id="@+id/btn_player3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="播放3" />

</LinearLayout>



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值