Android多媒体之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类是同步执行的只能一个文件一个文件的播放。
<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" > <Button android:id="@+id/play01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="play 01" /> <Button android:id="@+id/play02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="play 02" /> </LinearLayout>
package com.example.soundpooldemo; import java.util.HashMap; import java.util.Map; import android.media.AudioManager; import android.media.SoundPool; import android.media.SoundPool.OnLoadCompleteListener; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; @SuppressLint("UseSparseArrays") public class MainActivity extends Activity implements OnClickListener { private Button player1; private Button player2; private SoundPool sp; private Map<Integer,Integer> soundMap = new HashMap<Integer,Integer>(); private int loadFlag = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sp = new SoundPool(4, AudioManager.STREAM_MUSIC, 5); soundMap.put(1, sp.load(this, R.raw.xxxx, 1)); soundMap.put(2, sp.load(this, R.raw.yyyy, 1)); sp.setOnLoadCompleteListener(new OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { //判断是否加载完 loadFlag = 1; } }); player1 = (Button)findViewById(R.id.play01); player2 = (Button)findViewById(R.id.play02); player1.setOnClickListener(this); player2.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { if(loadFlag == 0) Toast.makeText(this, "音频正在加载中......", Toast.LENGTH_SHORT).show(); else { switch(v.getId()) { case R.id.play01: sp.play(soundMap.get(1), 1, 1, 1, 0, 1); break; case R.id.play02: sp.play(soundMap.get(2), 1, 1, 1, 0, 1); } } } }