android.media.soundpool的用法.load怎么填

Android中SoundPool的使用
大家知道MediaPlayer占用的资源比较多,且不可以同时支持播放多个音频,所以我们有一种叫做SoundPool,比如我们常见的按键音或者是手机提示音,还比如我们在游戏的开发中会有大量的音效效果等,下边介绍一下她的用法:
步骤如下:
1.创建SoundPool对象
*SoundPool源码中的构造方法方法体
* @param maxStreams 最多可以容纳多少个音频
* @param streamType 指定的声音类型,通过AudioManager类提供的常量进行指定
* @param srcQuality 指定音频的质量,默认为0
* @return a SoundPool object, or null if creation failed
public SoundPool(int maxStreams, int streamType, int srcQuality)
2.加载所需要播放的音频:
* @param context the application context
* @param resId the resource ID
* @param priority the priority of the sound. Currently has no effect. Use
a value of 1 for future compatibility.
* @return a sound ID. This value can be used to play or unload the sound.
public int load(Context context, int resId, int priority);
3.播放音频
* Play a sound from a sound ID.
* @param soundID
通过load方法返回的音频
* @param leftVolume
左声道的音量
* @param rightVolume 右声道的音量
* @param priority
优先级,值越大,优先级越高
* @param loop
循环的次数:0为不循环,-1为循环
* @param rate
指定速率,正常位1,为地位0.5,最高位2
* @return non-zero streamID if successful, zero if failed
public final int play(int soundID, float leftVolume, float rightVolume,
int priority, int loop, float rate);
4.案例如下:
(1)布局文件:
(2)MainActivity.java文件
package com.
import java.util.HashM
import android.app.A
import android.media.AudioM
import android.media.SoundP
import android.os.B
import android.view.KeyE
import android.view.V
import android.view.View.OnClickL
import android.widget.B
public class MainActivity extends Activity {
private SoundP
//声明一个SoundPool对象
//使用HashMap管理各种音频
private HashMap soundmap = new HashMap();
//创建一个HashMap对象
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button chimes = (Button) findViewById(R.id.button1);
//获取&风铃声&按钮
Button enter = (Button) findViewById(R.id.button2);
//获取&布谷鸟叫声&按钮
Button notify = (Button) findViewById(R.id.button3);
//获取&门铃声&按钮
Button ringout = (Button) findViewById(R.id.button4);
//获取&电话声&按钮
soundpool = new SoundPool(5,
AudioManager.STREAM_SYSTEM, 0); //创建一个SoundPool对象,该对象可以容纳5个音频流
//将要播放的音频流保存到HashMap对象中
soundmap.put(1, soundpool.load(this, R.raw.chimes, 1));
soundmap.put(2, soundpool.load(this, R.raw.enter, 1));
soundmap.put(3, soundpool.load(this, R.raw.notify, 1));
soundmap.put(4, soundpool.load(this, R.raw.ringout, 1));
soundmap.put(5, soundpool.load(this, R.raw.ding, 1));
//为各按钮添加单击事件监听器
chimes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
soundpool.play(soundmap.get(1), 1, 1, 0, 0, 1); //播放指定的音频
enter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
soundpool.play(soundmap.get(2), 1, 1, 0, 0, 1);//播放指定的音频
notify.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
soundpool.play(soundmap.get(3), 1, 1, 0, 0, 1);//播放指定的音频
ringout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
soundpool.play(soundmap.get(4), 1, 1, 0, 0, 1);//播放指定的音频
soundpool.play(soundpool.load(MainActivity.this, R.raw.notify, 1), 1, 1, 0, 0, 1);
//重写键被按下的事件
public boolean onKeyDown(int keyCode, KeyEvent event) {
soundpool.play(soundmap.get(5), 1, 1, 0, 0, 1);
//播放按键音
另外在资源文件中的raw文件中有几个小的铃声,这里不再显示。
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467142',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'[android] SoundPool详解
今天做一个小Demo用到了SoundPool,总结一下。
MediaPlayer缺点:不能重叠播放音乐,封装程度比较高,所以加载起来会比较慢。
SoundPool简介
提供了另一种播放音效的类。用来加载多个音效,短促音效和多个短促音效,可自行设置声音品质,音量,重复和优先级。在一定场合还是很好用的。
属于android.media包下,继承自Object。
public SoundPool(int maxStreams, int streamType, int srcQuality) {...} 参数一 maxStreams:支持多少个声音(也就是池的大小) 参数二 streamType:指定声音类型通过AudioManager获取对应的常量值。 参数三 srcQuality:采样率变换质量,没用到。默认是0,没查到资料。。
SoundPool pool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
指定了该池最多指定三个音频,使用用于系统声音的音频流。于AudioManager参数有很多,可以戳---& AudioManager。
有四个构造方法:
public int load(String path, int priority) 从完整文件路径名载入
path:文件路径
priority:优先级,0的优先级最低 返回值:这个声音的ID,用于打开和关闭音乐。 public int load(AssetFileDescriptor afd, int priority)
从Asset对象载入 afd:一个assets文件中的描述器,可以获得assets下文件的信息; priority: 返回值: public int load(Context context, int resId, int priority) 从APK资源获取
context: resId:文件的ID(res文件夹里的文件才有id) priority: public int load(FileDescriptor fd, long offset, long length, int priority) 从FileDescriptor对象载入
fd:文件描述类的实例 offset:从声音文件开始的偏移量(从什么地方播放) length:声音长度 priority:
构造方法: public final int play(int soundID, float leftVolume, float rightVolume,int priority, int loop, float rate) 参数一 soundID:所播放的声音ID,是load方法返回的 参数二 leftVolume:左音量,值从(0.0-1.0) 参数三 rightVolume:右音量,值从(0.0-1.0) 参数四 priority:优先级,0的优先级最低。 参数五 loop:是否循环,0不循环,-1一直循环。 参数六 rate:播放速率,1为正常速率。范围从0.5-2。
如果需要播放多首:需要一个集合来存储音频的ID,就是上面load方法返回的int。 如果指定播放一首:就不用建集合了,假设音频位于
//获取资源
AssetFileDescriptor fd = getResources().openRawResourceFd(R.raw.music)
//加载音频
int soundID = pool.load(fd, 1);
//播放音频,soundID是上面的返回值
pool.play(soundID, 1, 1, 0, 0, 1);
这样完成了一首音频的播放。 最后一个问题:播放多首音频。
声明一个集合存放音频 HashMap soundMap = new HashMap();
soundMap.put(1, pool.load(this, R.raw.music1, 1));
soundMap.put(2, pool.load(this, R.raw.music2, 1));
soundMap.put(3, pool.load(this, R.raw.music3, 1));
存放三个音频; pool.play(soundMap.get(1), 1, 1, 0, 0, 1);
pool.play(soundMap.get(2), 1, 1, 0, 0, 1);
pool.play(soundMap.get(3), 1, 1, 0, 0, 1);
这样就完成多首音频的播放
释放资源及其他
release()方法释放所有SoundPool对象占据的内存和资源。
pause(soundID)暂停播放
stop(soundID)停止播放
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467142',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'Java Code Example android.media.SoundPool
Java Code Examples for android.media.SoundPool
The following are top voted examples for showing how to use
android.media.SoundPool. These examples are extracted from open source projects.
You can vote up the examples you like and your votes will be used in our system to product
more good examples.
+ Save this class to your library
@SuppressLint(&NewApi&)
public SoundPlayer(Context mContext, AssetFileDescriptor afd1) {
mAfd = afd1;
mAudioStreamType = AudioManager.STREAM_SYSTEM;
audio = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
if (mPlayer == null) {
if (android.os.Build.VERSION.SDK_INT &= android.os.Build.VERSION_CODES.LOLLIPOP) {
mPlayer = new SoundPool.Builder()
.setMaxStreams(5)
.setAudioAttributes(
new AudioAttributes.Builder()
.setLegacyStreamType(mAudioStreamType)
.setContentType(
AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()).build();
mPlayer = new SoundPool(5, mAudioStreamType, 0);
soundStartId = mPlayer.load(mAfd, 1);
mAfd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
private Sounds(Context pContext) {
mMusic = MediaPlayer.create(pContext, R.raw.music);
mMusic.setLooping(true);
mMusic.setVolume(0.5f, 0.5f);
mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
mLoaded++;
mSounds = new int[3];
mSounds[0] = mSoundPool.load(pContext, R.raw.sound0, 1);
mSounds[1] = mSoundPool.load(pContext, R.raw.sound1, 1);
mSounds[2] = mSoundPool.load(pContext, R.raw.sound2, 1);
public SoundManager(Context context) {
this.context =
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
sm = new int[FrozenBubble.NUM_SOUNDS];
sm[FrozenBubble.SOUND_WON] = soundPool.load(context, R.raw.applause, 1);
sm[FrozenBubble.SOUND_LOST] = soundPool.load(context, R.raw.lose, 1);
sm[FrozenBubble.SOUND_LAUNCH] = soundPool.load(context, R.raw.launch, 1);
sm[FrozenBubble.SOUND_DESTROY] =
soundPool.load(context, R.raw.destroy_group, 1);
sm[FrozenBubble.SOUND_REBOUND] =
soundPool.load(context, R.raw.rebound, 1);
sm[FrozenBubble.SOUND_STICK] = soundPool.load(context, R.raw.stick, 1);
sm[FrozenBubble.SOUND_HURRY] = soundPool.load(context, R.raw.hurry, 1);
sm[FrozenBubble.SOUND_NEWROOT] =
soundPool.load(context, R.raw.newroot_solo, 1);
sm[FrozenBubble.SOUND_NOH] = soundPool.load(context, R.raw.noh, 1);
private void initSoundPool() {
synchronized (this) {
if (mSoundPool == null) {
mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);
mTapSound = mSoundPool.load(this, R.raw.tap, 1);
public ScouterDrawer(Context context) {
mCountDownView = new CountDownView(context);
mCountDownView.setCountDown(COUNT_DOWN_VALUE);
mCountDownView.setListener(new CountDownView.CountDownListener() {
public void onTick(long millisUntilFinish) {
draw(mCountDownView);
public void onFinish() {
mCountDownDone =
mChronometerView.setBaseMillis(SystemClock.elapsedRealtime());
if (mHolder != null) {
mChronometerView.start();
/* This is actually the OVER NINE THOUSAND clip... */
playSound(mCountDownSoundId);
mChronometerView = new ScouterView(context);
mChronometerView.setListener(new ScouterView.ChangeListener() {
public void onChange() {
draw(mChronometerView);
mChronometerView.setForceStart(true);
mSoundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
mStartSoundId = mSoundPool.load(context, R.raw.start, SOUND_PRIORITY);
mCountDownSoundId = mSoundPool.load(context, R.raw.countdown_bip, SOUND_PRIORITY);
public SoundPoolPlayer(Context context) {
mContext =
mSoundIDToPlay = ID_NOT_LOADED;
mSoundPool = new SoundPool(NUM_SOUND_STREAMS, getAudioTypeForSoundPool(), 0);
mSoundPool.setOnLoadCompleteListener(this);
mSoundIDs = new int[SOUND_RES.length];
mSoundIDReady = new boolean[SOUND_RES.length];
for (int i = 0; i & SOUND_RES. i++) {
mSoundIDs[i] = mSoundPool.load(mContext, SOUND_RES[i], 1);
mSoundIDReady[i] =
public void surfaceCreated(SurfaceHolder holder) {
// surface has been created, acquire camera and tell it where to draw
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
} catch (Exception e) {
if (MediaPhone.DEBUG)
Log.d(DebugUtilities.getLogTag(this), &surfaceCreated() -& setPreviewDisplay()&, e);
mFocusSoundId = -1;
mFocusSoundPlayer = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);
mFocusSoundPlayer.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
mFocusSoundId = sampleId;
mFocusSoundPlayer.load(getContext(), R.raw.af_success, 1);
public void initSwitchSound() {
if (enableSound && (isSoundInit == false || soundPool == null)) {
soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(soundInitListener);
switchSound = soundPool.load(FlashApp.getContext(),
R.raw.flashswitch, 1);
public static void playSound() {
if (AppSettings.isRefreshSound() && BaseActivity.getRunningActivity() != null) {
SoundPool soundPool= new SoundPool(10, AudioManager.STREAM_SYSTEM,5);
soundPool.load(BaseActivity.getRunningActivity(), R.raw.pull_event, 1);
soundPool.play(1, 1, 1, 0, 0, 1);
Example 10
* Generate a sound with specific characteristics.
private Sound generateSound(SoundPool soundPool, File dir, String name, int lengthMsec,
int freqHz) {
* Since we're generating trivial tones, we could just generate a short set of samples
* and then set a nonzero loop count in SoundPool.
We could also generate it at twice
* the frequency for half the duration, and then use a playback rate of 0.5.
These would
* save space on disk and in memory, but our sounds are already pretty tiny.
* These files can be erased by the user (using the &clear app data&) function, so we
* need to be able to regenerate them.
If they already exist we can skip the process
* and save some wear on flash memory.
Sound sound =
File outFile = new File(dir, name + &.wav&);
if (!outFile.exists()) {
FileOutputStream fos = new FileOutputStream(outFile);
// Number of samples.
Not worried about int overflow for our short sounds.
int sampleCount = lengthMsec * SAMPLE_RATE / 1000;
ByteBuffer buf = generateWavHeader(sampleCount);
byte[] array = buf.array();
fos.write(array);
buf = generateWavData(sampleCount, freqHz);
array = buf.array();
fos.write(array);
fos.close();
Log.d(TAG, &Wrote sound file & + outFile.toString());
} catch (IOException ioe) {
Log.e(TAG, &sound file op failed: & + ioe.getMessage());
throw new RuntimeException(ioe);
//Log.d(TAG, &Sound '& + outFile.getName() + &' exists, not regenerating&);
int handle = soundPool.load(outFile.toString(), 1);
return new Sound(name, soundPool, handle);
Example 11
public SoundPoolPlayer(Context context) {
mContext =
mSoundIDToPlay = ID_NOT_LOADED;
mSoundPool = new SoundPool(NUM_SOUND_STREAMS, getAudioTypeForSoundPool(), 0);
mSoundPool.setOnLoadCompleteListener(this);
mSoundIDs = new int[SOUND_RES.length];
mSoundIDReady = new boolean[SOUND_RES.length];
for (int i = 0; i & SOUND_RES. i++) {
mSoundIDs[i] = mSoundPool.load(mContext, SOUND_RES[i], 1);
mSoundIDReady[i] =
Example 12
protected void onResume() {
super.onResume();
// Manage bubble popping sound
// Use AudioManager.STREAM_MUSIC as stream type
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
mStreamVolume = (float) mAudioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)
/ mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
// TODO - make a new SoundPool, allowing up to 10 streams
mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
// TODO - set a SoundPool OnLoadCompletedListener that calls setupGestureDetector()
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
if (0 == status) {
setupGestureDetector();
// TODO - load the sound from res/raw/bubble_pop.wav
mSoundID = mSoundPool.load(this, R.raw.bubble_pop, 1);
Example 13
private int initSoundPool(int numStreams) throws java.lang.InterruptedException {
if (mSoundPool != null) {
if ((mMaxStreams == numStreams) && (mLoadStatus == 0)) return mLoadS
mSoundPool.release();
mSoundPool =
// create sound pool
mLoadStatus = 0;
mMaxStreams = numS
mSoundPool = new SoundPool(numStreams, AudioSystem.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new LoadCompleteCallback());
int numSounds = mTestFiles.
mSounds = new int[numSounds];
// load sounds
synchronized(mSoundPool) {
for (int index = 0; index & numS index++) {
mSounds[index] = loadSound(mTestFiles[index], NORMAL_PRIORITY);
mLastSample = mSounds[index];
mSoundPool.wait();
return mLoadS
Example 14
* Construct a new MediaActionSound instance. Only a single instance is
* needed for playing any platfor you do not need a
* separate instance for each sound type.
public MediaActionSound() {
mSoundPool = new SoundPool(NUM_MEDIA_SOUND_STREAMS,
AudioManager.STREAM_SYSTEM_ENFORCED, 0);
mSoundPool.setOnLoadCompleteListener(mLoadCompleteListener);
mSoundIds = new int[SOUND_FILES.length];
for (int i = 0; i & mSoundIds. i++) {
mSoundIds[i] = SOUND_NOT_LOADED;
mSoundIdToPlay = SOUND_NOT_LOADED;
Example 15
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_surprise);
mDensity = getResources().getDisplayMetrics().
mFishWidth = (int) (83 * mDensity);
mFishHeight = (int) (mFishWidth * 85.f / 166);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mContainer = (FrameLayout) findViewById(android.R.id.content);
mCloseButton = (ImageButton) findViewById(R.id.button_close);
DisplayMetrics metrics = getResources().getDisplayMetrics();
mScreenWidth = metrics.widthP
mScreenHeight = metrics.heightP
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bubble);
mBubbleWidth = bitmap.getWidth();
mBubbleHeight = bitmap.getHeight();
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
mSoundLoaded =
mSoundId = mSoundPool.load(this, R.raw.bubble, 1);
mPlayer = MediaPlayer.create(this, R.raw.water);
mPlayer.setLooping(true);
mPlayer.start();
HttpUtils.get(&http://u148.oss-cn-/image/easter&, EasterData.class, this, this);
Example 16
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
CharadesModel model = (CharadesModel) getIntent().getSerializableExtra(EXTRA_MODEL);
mCardMargin = (int) getResources().getDimension(R.dimen.card_margin);
mCardScroller = new CardScrollView(this);
mCardScroller.setHorizontalScrollBarEnabled(true);
mCardScroller.setAdapter(
new CharadesResultsAdapter(getLayoutInflater(), getResources(), model));
mCardScroller.setOnItemClickListener(mOnClickListener);
mCardScroller.activate();
setContentView(mCardScroller);
// Initialize the sound pool and play the losing or winning sound immediately once it has
// been loaded.
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
soundPool.play(sampleId, 1.0f, 1.0f, 0, 0, 1.0f);
int soundResId = model.areAllPhrasesGuessedCorrectly() ?
R.raw.triumph : R.raw.sad_
mSoundPool.load(this, soundResId, 0);
Example 17
public BeepThread(Context context, KalmanFilteredVario vario) {
this.vario =
SharedPreferences sharedPrefs = BFVSettings.sharedP
base = Integer.valueOf(sharedPrefs.getString(&audio_basehz&, &1000&));
increment = Integer.valueOf(sharedPrefs.getString(&audio_incrementhz&, &100&));
varioAudioCutoff = Double.valueOf(sharedPrefs.getString(&vario_audio_cutoff&, &0.05&));
varioAudioThreshold = Double.valueOf(sharedPrefs.getString(&vario_audio_threshold&, &0.2&));
sinkAudioThreshold = Double.valueOf(sharedPrefs.getString(&sink_audio_threshold&, &-2.0&));
sinkAudioCutoff = Double.valueOf(sharedPrefs.getString(&sink_audio_cutoff&, &-1.5&));
sinkBase = Integer.valueOf(sharedPrefs.getString(&sink_audio_basehz&, &500&));
sinkIncrement = Integer.valueOf(sharedPrefs.getString(&sink_audio_incrementhz&, &100&));
cadenceFunction = new PiecewiseLinearFunction(new Point2d(0, 0.4763));
cadenceFunction.addNewPoint(new Point2d(0.135, 0.4755));
cadenceFunction.addNewPoint(new Point2d(0.441, 0.3619));
cadenceFunction.addNewPoint(new Point2d(1.029, 0.2238));
cadenceFunction.addNewPoint(new Point2d(1.559, 0.1565));
cadenceFunction.addNewPoint(new Point2d(2.471, 0.0985));
cadenceFunction.addNewPoint(new Point2d(3.571, 0.0741));
soundPool = new SoundPool(numSounds, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(this);
tone_1000 = soundPool.load(context, R.raw.tone_1000mhz, 1);
sink = soundPool.load(context, R.raw.sink_tone500mhz, 1);
Example 18
public SoundPoolPlayer(Context context) {
mContext =
int audioType = ApiHelper.getIntFieldIfExists(AudioManager.class,
&STREAM_SYSTEM_ENFORCED&, null, AudioManager.STREAM_RING);
mSoundIDToPlay = ID_NOT_LOADED;
mSoundPool = new SoundPool(NUM_SOUND_STREAMS, audioType, 0);
mSoundPool.setOnLoadCompleteListener(this);
mSoundIDs = new int[SOUND_RES.length];
mSoundIDReady = new boolean[SOUND_RES.length];
for (int i = 0; i & SOUND_RES. i++) {
mSoundIDs[i] = mSoundPool.load(mContext, SOUND_RES[i], 1);
mSoundIDReady[i] =
Example 19
public SoundPoolPlayer(Context context) {
mContext =
mSoundIDToPlay = ID_NOT_LOADED;
mSoundPool = new SoundPool(NUM_SOUND_STREAMS, getAudioTypeForSoundPool(), 0);
mSoundPool.setOnLoadCompleteListener(this);
mSoundIDs = new int[SOUND_RES.length];
mSoundIDReady = new boolean[SOUND_RES.length];
for (int i = 0; i & SOUND_RES. i++) {
mSoundIDs[i] = mSoundPool.load(mContext, SOUND_RES[i], 1);
mSoundIDReady[i] =
Example 20
private int initSoundPool(int numStreams) throws java.lang.InterruptedException {
if (mSoundPool != null) {
if ((mMaxStreams == numStreams) && (mLoadStatus == 0)) return mLoadS
mSoundPool.release();
mSoundPool =
// create sound pool
mLoadStatus = 0;
mMaxStreams = numS
mSoundPool = new SoundPool(numStreams, AudioSystem.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new LoadCompleteCallback());
int numSounds = mTestFiles.
mSounds = new int[numSounds];
// load sounds
synchronized(mSoundPool) {
for (int index = 0; index & numS index++) {
mSounds[index] = loadSound(mTestFiles[index], NORMAL_PRIORITY);
mLastSample = mSounds[index];
mSoundPool.wait();
return mLoadS
Example 21
protected void onResume() {
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, SRC_QUALITY);
soundPool.setOnLoadCompleteListener(this);
aMgr = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
sid_background = soundPool.load(this, R.raw.crickets, PRIORITY);
sid_chimp = soundPool.load(this, R.raw.chimp, PRIORITY);
sid_rooster = soundPool.load(this, R.raw.rooster, PRIORITY);
sid_roar = soundPool.load(this, R.raw.roar, PRIORITY);
AssetFileDescriptor afd = this.getAssets().openFd(&dogbark.mp3&);
sid_bark = soundPool.load(afd.getFileDescriptor(), 0,
afd.getLength(), PRIORITY);
afd.close();
} catch (IOException e) {
e.printStackTrace();
// sid_bark = soundPool.load(&/mnt/sdcard/dogbark.mp3&, PRIORITY);
super.onResume();
Example 22
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
if (Build.VERSION.SDK_INT &= 11) {
HoneycombHelper.fullScreen(this);
mHasDigitizer = getPackageManager().hasSystemFeature(
&android.hardware.touchscreen.pen&);
mText = (EditText) findViewById(R.id.text);
mTextAsImages = (FlowLayout) findViewById(R.id.text_as_images);
mParser = new PlaFileParser();
setValuesFromSavedInstanceState(savedInstanceState);
mSoundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
mSoundPool.setOnLoadCompleteListener(this);
Example 23
private int initSoundPool(int numStreams) throws java.lang.InterruptedException {
if (mSoundPool != null) {
if ((mMaxStreams == numStreams) && (mLoadStatus == 0)) return mLoadS
mSoundPool.release();
mSoundPool =
// create sound pool
mLoadStatus = 0;
mMaxStreams = numS
mSoundPool = new SoundPool(numStreams, AudioSystem.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new LoadCompleteCallback());
int numSounds = mTestFiles.
mSounds = new int[numSounds];
// load sounds
synchronized(mSoundPool) {
for (int index = 0; index & numS index++) {
mSounds[index] = loadSound(mTestFiles[index], NORMAL_PRIORITY);
mLastSample = mSounds[index];
mSoundPool.wait();
return mLoadS
Example 24
private void playSound() {
if (mSoundResDef != -1) {
if (mSoundPool == null) {
mSoundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
mSoundPool.setOnLoadCompleteListener(this);
mSoundId = mSoundPool.load(getContext(), mSoundResDef, 0);
mSoundPool.play(mSoundId, 1, 1, 0, 0, 1);
} catch (Exception e) {
e.printStackTrace();
Example 25
public void onLoadComplete(SoundPool soundPool,
int sampleId, int status) {
if (status == 0) {
if (mSoundIdToPlay == sampleId) {
soundPool.play(sampleId, 1.0f, 1.0f, 0, 0, 1.0f);
mSoundIdToPlay = SOUND_NOT_LOADED;
Log.e(TAG, &Unable to load sound for playback (status: & +
status + &)&);
Example 26
public void onLoadComplete(SoundPool soundPool,
int sampleId, int status) {
if (status == 0) {
if (mSoundIdToPlay == sampleId) {
soundPool.play(sampleId, 1.0f, 1.0f, 0, 0, 1.0f);
mSoundIdToPlay = SOUND_NOT_LOADED;
Log.e(TAG, &Unable to load sound for playback (status: & +
status + &)&);
Example 27
private void makeSound(){
if(isMute()) {
SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
int soundClick = -1;
boolean success =
soundClick = sp.load(settings.getContext().getAssets().openFd(&sounds/airhorn.ogg&), 1);
} catch (IOException e){
e.printStackTrace();
if (success){
sp.play(soundClick, 1 ,1, 0, 0, 1);
Example 28
public void onLoadComplete(SoundPool sPool, int sid, int status) {
Log.v(&soundPool&, &sid & + sid + & loaded with status & + status);
final float currentVolume = ((float) aMgr
.getStreamVolume(AudioManager.STREAM_MUSIC))
/ ((float) aMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
if (status != 0)
if (sid == sid_background) {
if (sPool.play(sid, currentVolume, currentVolume, PRIORITY, -1,
1.0f) == 0)
Log.v(&soundPool&, &Failed to start sound&);
} else if (sid == sid_chimp) {
queueSound(sid, 5000, currentVolume);
} else if (sid == sid_rooster) {
queueSound(sid, 6000, currentVolume);
} else if (sid == sid_roar) {
queueSound(sid, 12000, currentVolume);
} else if (sid == sid_bark) {
queueSound(sid, 7000, currentVolume);
Example 29
public void onLoadComplete(SoundPool sp, int id, int status) {
Log.v(&open & + id + & & + status);
if (mPendingSound == id) {
sp.play(id, 1, 1, 0, 0, 1);
Example 30
public void onLoadComplete(SoundPool soundPool,
int sampleId, int status) {
if (status == 0) {
if (mSoundIdToPlay == sampleId) {
soundPool.play(sampleId, 1.0f, 1.0f, 0, 0, 1.0f);
mSoundIdToPlay = SOUND_NOT_LOADED;
Log.e(TAG, &Unable to load sound for playback (status: & +
status + &)&);
Example 31
public void updateLocation(double lat, double lon) {
// update state of inArea and eventually call hooks
super.updateLocation(lat, lon);
if (soundId == -1) {
Log.e(TAG, String.format(&Sound '%s' is not loaded&, value));
// start/stop playing sound or update volume
double distance = GPoint.distanceBetween(point.latitude, point.longitude, lat, lon);
boolean r = distance & (soundRadius + (inSoundRadius ? LEAVE_RADIUS : 0));
float actualVolume = calcVolume(distance);
SoundPool soundPool = getScenario().getSoundPool();
if (inSoundRadius != r) {
inSoundRadius =
if (inSoundRadius) {
Log.d(TAG, String.format(&Started playing sound '%s' at volume '%.2f'&, value, actualVolume));
soundPool.play(soundId, actualVolume, actualVolume, 1, loop, pitch);
Log.d(TAG, String.format(&Stopped playing sound '%s'&, value));
soundPool.stop(soundId);
} else if (inSoundRadius) {
// update sound volume
Log.d(TAG, String.format(&Changed volume of sound '%s' to '%.2f'&, value, actualVolume));
soundPool.setVolume(soundId, actualVolume, actualVolume);
Example 32
@SuppressWarnings(&deprecation&)
@SuppressLint(&InlinedApi&)
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.d(TermDebug.LOG_TAG, &Terminal started&);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mSettings = new TermSettings(getResources(), mPrefs);
Intent broadcast = new Intent(ACTION_PATH_BROADCAST);
if (AndroidCompat.SDK &= 12) {
broadcast.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
mPendingPathBroadcasts++;
sendOrderedBroadcast(broadcast, PERMISSION_PATH_BROADCAST,
mPathReceiver, null, RESULT_OK, null, null);
broadcast = new Intent(broadcast);
broadcast.setAction(ACTION_PATH_PREPEND_BROADCAST);
mPendingPathBroadcasts++;
sendOrderedBroadcast(broadcast, PERMISSION_PATH_PREPEND_BROADCAST,
mPathReceiver, null, RESULT_OK, null, null);
// TSIntent = new Intent(this, TermService.class);
// startService(TSIntent);
// if (!bindService(TSIntent, mTSConnection, BIND_AUTO_CREATE)) {
// Log.e(TermDebug.LOG_TAG, &could not start service&);
if (AndroidCompat.SDK &= 11) {
int actionBarMode = mSettings.actionBarMode();
mActionBarMode = actionBarM
switch (actionBarMode) {
case TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE:
setTheme(R.style.Theme_Holo);
case TermSettings.ACTION_BAR_MODE_HIDES:
setTheme(R.style.Theme_Holo_ActionBarOverlay);
setContentView(R.layout.term_activity);
mViewFlipper = (TermViewFlipper) findViewById(VIEW_FLIPPER);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
TermDebug.LOG_TAG);
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int wifiLockMode = WifiManager.WIFI_MODE_FULL;
if (AndroidCompat.SDK &= 12) {
wifiLockMode = WIFI_MODE_FULL_HIGH_PERF;
mWifiLock = wm.createWifiLock(wifiLockMode, TermDebug.LOG_TAG);
ActionBarCompat actionBar = ActivityCompat.getActionBar(this);
if (actionBar != null) {
mActionBar = actionB
actionBar.setNavigationMode(ActionBarCompat.NAVIGATION_MODE_LIST);
actionBar.setDisplayOptions(0, ActionBarCompat.DISPLAY_SHOW_TITLE);
if (mActionBarMode == TermSettings.ACTION_BAR_MODE_HIDES) {
actionBar.hide();
mHaveFullHwKeyboard = checkHaveFullHwKeyboard(getResources()
.getConfiguration());
// ///////////////////////////////////////
mSoundPoll = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
mBellSoundId = mSoundPoll.load(this, R.raw.bell, 1);
TSIntent = new Intent(this, TermService.class);
startService(TSIntent);
if (!bindService(TSIntent, mTSConnection, BIND_AUTO_CREATE)) {
Log.e(TermDebug.LOG_TAG, &could not start service&);
// ///////////////////////////////////////
updatePrefs();
mAlreadyStarted =
mFunctionReciver = new TermFunctionReciver(getCurrentTermSession());
IntentFilter filter = new IntentFilter();
filter.addAction(TermFunctionReciver.ACTION);
registerReceiver(mFunctionReciver, filter);
Example 33
* Construct a KeyguardViewMediator
* @param context
* @param lockPatternUtils optional mock interface for LockPatternUtils
public KeyguardViewMediator(Context context, LockPatternUtils lockPatternUtils) {
mContext =
mPM = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, &show keyguard&);
mShowKeyguardWakeLock.setReferenceCounted(false);
mWakeAndHandOff = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, &keyguardWakeAndHandOff&);
mWakeAndHandOff.setReferenceCounted(false);
mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mUpdateMonitor = KeyguardUpdateMonitor.getInstance(context);
mLockPatternUtils = lockPatternUtils != null
? lockPatternUtils : new LockPatternUtils(mContext);
mLockPatternUtils.setCurrentUser(UserHandle.USER_OWNER);
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
mKeyguardViewManager = new KeyguardViewManager(context, wm, mViewMediatorCallback,
mLockPatternUtils);
mUserPresentIntent = new Intent(Intent.ACTION_USER_PRESENT);
mUserPresentIntent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
| Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
final ContentResolver cr = mContext.getContentResolver();
mShowLockIcon = (Settings.System.getInt(cr, &show_status_bar_lock&, 0) == 1);
mScreenOn = mPM.isScreenOn();
mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
if (soundPath != null) {
mLockSoundId = mLockSounds.load(soundPath, 1);
if (soundPath == null || mLockSoundId == 0) {
Log.w(TAG, &failed to load lock sound from & + soundPath);
soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
if (soundPath != null) {
mUnlockSoundId = mLockSounds.load(soundPath, 1);
if (soundPath == null || mUnlockSoundId == 0) {
Log.w(TAG, &failed to load unlock sound from & + soundPath);
int lockSoundDefaultAttenuation = context.getResources().getInteger(
com.android.internal.R.integer.config_lockSoundVolumeDb);
mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
Example 34
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String DB_PATH = MainActivity.this.getFilesDir().getParent() + &/databases/&;
String DB_NAME = &restaurant.db&;
if (!(new File(DB_PATH + DB_NAME)).exists()) {
File file = new File(DB_PATH);
if (!file.exists()) {
file.mkdir();
InputStream inputStream = getBaseContext().getAssets().open(DB_NAME);
OutputStream outputStream = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
while ((length = inputStream.read(buffer)) & 0) {
outputStream.write(buffer, 0, length);
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
Toast.makeText(
MainActivity.this,
getString(R.string.error_database_copy),
Toast.LENGTH_SHORT
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(
new ArrayAdapter&String&(
MainActivity.this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
new String[] {
getString(R.string.main_dropdown_random),
getString(R.string.main_dropdown_usual)
sharedPreferences = getSharedPreferences(&setting&, MODE_PRIVATE);
editor = sharedPreferences.edit();
String path = sharedPreferences.getString(&bitmap_background&, null);
background = (ImageView) findViewById(R.id.main_background_image);
if (path != null) {
Uri uri = Uri.parse(path);
background.setImageURI(uri);
background.setImageResource(R.drawable.main_background);
popupView = getLayoutInflater().inflate(R.layout.popup, null);
popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
/* Do something */
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 5);
soundID = soundPool.load(this, R.raw.dang, 1);

我要回帖

更多关于 soundpool load 的文章

 

随机推荐