转载请说明出处!
作者:kqw攻城狮
出处:个人站 | CSDN
有些时候程序需要播放几个很短的低延迟的音效来响应与用户的交互。
Android通过SoundPool
将文件音频缓存加载到内存中,然后在响应用户操作的时候快速地播放。
Android框架低通了SoundPool来解码小音频文件,并在内存中操作它们来进行音频快速和重复的播放。SoundPool还有一些其他特性,比如可以在运行时控制音量和播放速度。
播放音效也很简单,总共分5步
准备音频文件
将音频文件放置在assets目录下
初始化SoundPool
SoundPool mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
加载音频文件
int streamID = mSoundPool.load(getApplicationContext().getAssets().openFd("beep/beep1.mp3"), 1);
播放音频文件
mSoundPool.play(streamID, 10, 10, 1, 0, 1.0f);
释放SoundPool
mSoundPool.release();
mSoundPool = null;
Code
package com.kongqw.kqwplaybeepdemo;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private SoundPool mSoundPool;
private int streamID;
private HashMap<String, Integer> mSoundMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_beep1).setOnClickListener(this);
findViewById(R.id.button_beep2).setOnClickListener(this);
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSoundMap = new HashMap<>();
try {
streamID = mSoundPool.load(getApplicationContext().getAssets().openFd("beep/beep1.mp3"), 1);
mSoundMap.put("beep1.mp3", streamID);
streamID = mSoundPool.load(getApplicationContext().getAssets().openFd("beep/beep2.mp3"), 1);
mSoundMap.put("beep2.mp3", streamID);
Log.i(TAG, "onCreate: streamID = " + streamID);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mSoundPool.release();
mSoundPool = null;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_beep1:
streamID = mSoundMap.get("beep1.mp3");
mSoundPool.play(streamID, 10, 10, 1, 0, 1.0f);
break;
case R.id.button_beep2:
streamID = mSoundMap.get("beep2.mp3");
mSoundPool.play(streamID, 10, 10, 1, 0, 1.0f);
break;
default:
break;
}
}
}