Android播放音效


转载请说明出处!
作者:kqw攻城狮
出处:个人站 | CSDN


有些时候程序需要播放几个很短的低延迟的音效来响应与用户的交互。

Android通过SoundPool将文件音频缓存加载到内存中,然后在响应用户操作的时候快速地播放。
Android框架低通了SoundPool来解码小音频文件,并在内存中操作它们来进行音频快速和重复的播放。SoundPool还有一些其他特性,比如可以在运行时控制音量和播放速度。

播放音效也很简单,总共分5步

准备音频文件

将音频文件放置在assets目录下

准备音频文件

初始化SoundPool

1
SoundPool mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);

加载音频文件

1
int streamID = mSoundPool.load(getApplicationContext().getAssets().openFd("beep/beep1.mp3"), 1);

播放音频文件

1
mSoundPool.play(streamID, 10, 10, 1, 0, 1.0f);

释放SoundPool

1
2
mSoundPool.release();
mSoundPool = null;

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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;
}
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!