现在的位置: 首页 > 综合 > 正文

Android应用:SoundPool 播放音效

2013年10月19日 ⁄ 综合 ⁄ 共 5672字 ⁄ 字号 评论关闭

1.SoundPool 简介

开发Android软件中我们可能经常需播放多媒体声音文件,一般使用MediaPlayer
但该类占用资源较多,对于游戏等应用可能不是很适合,SoundPool类在SDK
android.media.SoundPool,顾名思义是声音池的意思。主要播放一些较短的声音
片段,可以从程序的资源或文件系统加载,相对于MediaPlayer类可以做到使用较少
CPU资源和较短的反应延迟。
     SoundPool和其他声音播放类相比,其特点是可以自行设置声音的
品质、音量、播放比率等参等。并且它可以同时管理多个音频流,每个
流都有独自的ID,对某个音频流的管理都是通过ID进行的。

2 使用方法

SoundPool基本使用方法:

              1. 创建一个SoundPool 

                 创建一个SoundPool对象:new SoundPool(int maxStreams, int streamType, int srcQuality);

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

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

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

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

                  eg. 

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

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

          2、 从资源或者文件载入音频流: load(Context context, int resId, int priority);

                    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)  //从完整文件路径名载入 

                                  最后一个参数为优先级。

                         一般把多个声音放到HashMap中去,比如 

                         soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); 

                         soundPoolMap = new HashMap<Integer, Integer>();   

                         soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong, 1));

          3、  播放声音play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate);

                     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开始。


3. soundpool一个小应用

布局 xml 代码:

<RelativeLayout 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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="播放音效1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/button1"
        android:text="播放音效2" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:text="暂停音效1" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button3"
        android:layout_below="@+id/button3"
        android:text="暂停音效2" />

</RelativeLayout>
java 代码:

package com.example.android_sample_3_1;

import java.util.HashMap;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	SoundPool sp;
	HashMap<Integer, Integer> spMap;
	Button b1;
	Button b1Pause;
	Button b2;
	Button b2Pause;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initSoundPool();
		b1 = (Button) findViewById(R.id.button1);
		b1Pause = (Button) findViewById(R.id.button3);
		b2 = (Button) findViewById(R.id.button2);
		b2Pause = (Button) findViewById(R.id.button4);
		
		b1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				palySound(1, 1);
				Toast.makeText(MainActivity.this, "播放音效1", Toast.LENGTH_SHORT).show();
			}
		});
		b1Pause.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				sp.pause(spMap.get(1));
				Toast.makeText(MainActivity.this, "暂停音效1", Toast.LENGTH_SHORT).show();
			}
		});
		b2.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				palySound(2, 1);
				Toast.makeText(MainActivity.this, "播放音效2", Toast.LENGTH_SHORT).show();
			}
		});
		b2Pause.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				sp.pause(spMap.get(2));
				Toast.makeText(MainActivity.this, "暂停音效2", Toast.LENGTH_SHORT).show();
			}
		});
	}
	private void palySound(int sound, int number) {
		AudioManager am = (AudioManager) this.getSystemService(this.AUDIO_SERVICE);
		float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		float volumnRatio = audioCurrentVolumn / audioMaxVolumn;
		sp.play(spMap.get(sound), volumnRatio, volumnRatio, 1, number, 1);
		
	}
	private void initSoundPool() {
		sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
		spMap = new HashMap<Integer, Integer>();
		spMap.put(1, sp.load(this, R.raw.attack02, 1));
		spMap.put(2, sp.load(this, R.raw.attack14, 1));
	}

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

}


抱歉!评论已关闭.