public class MyAudioControl {
private final Context mContext;
private AudioManager mAudioManager;
private SoundPool mSoundPool;
private int mStream;
/**
*
* @param context Context
* @return MyAudioControl
*/
public static MyAudioControl get(Context context) {
return new MyAudioControl(context, AudioManager.STREAM_MUSIC);
}
/**
*
* @param context Context
* @param stream int
* @return SkAudioControl
*/
public static MyAudioControl get(Context context, int stream) {
return new MyAudioControl(context, stream);
}
/**
*
* @param context Context
* @param stream int
*/
private MyAudioControl(Context context, int stream) {
mContext = context;
mStream = stream;
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
mSoundPool = new SoundPool(1, mStream, 1);
mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
float soundValue = (float) getSoundValue();
float soundMaxValue = (float) getSoundMaxValue();
float value = soundValue / soundMaxValue;
soundPool.play(sampleId, value, value, 1, 0, 1);
}
});
}
/**
*
* @return int
*/
private int getSoundValue() {
return mAudioManager.getStreamVolume(mStream);
}
/**
*
* @return int
*/
private int getSoundMaxValue() {
return mAudioManager.getStreamMaxVolume(mStream);
}
/**
*
* @param fileName String
*/
public void play(String fileName) {
if (mAudioManager.getStreamVolume(mStream) == 0) {
return;
}
AssetFileDescriptor afd = null;
try {
afd = mContext.getAssets().openFd("sounds/" + fileName + ".mp3");
} catch (IOException e) {
e.printStackTrace();
}
mSoundPool.load(afd, 1);
}
}