下面列出了怎么用android.media.AudioAttributes的API类实例代码及写法,或者点击链接到github查看源代码。
public AndroidAudioPlayer(final AudioConfig audioConfig) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setLegacyStreamType(AudioManager.STREAM_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
AudioFormat audioFormat = new AudioFormat.Builder()
.setChannelMask(audioConfig.getOutputChannel())
.setEncoding(audioConfig.getOutputFormat())
.setSampleRate(audioConfig.getSampleRate())
.build();
audioTrack = new AudioTrack(audioAttributes,
audioFormat,
audioConfig.getOutputBufferSize(),
AudioTrack.MODE_STATIC,
AudioManager.AUDIO_SESSION_ID_GENERATE);
outputByteCount = audioConfig.getOutputFormatByteCount();
}
public MediaSessionRecord(int ownerPid, int ownerUid, int userId, String ownerPackageName,
ISessionCallback cb, String tag, MediaSessionService service, Looper handlerLooper) {
mOwnerPid = ownerPid;
mOwnerUid = ownerUid;
mUserId = userId;
mPackageName = ownerPackageName;
mTag = tag;
mController = new ControllerStub();
mSession = new SessionStub();
mSessionCb = new SessionCb(cb);
mService = service;
mContext = mService.getContext();
mHandler = new MessageHandler(handlerLooper);
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
mAudioManagerInternal = LocalServices.getService(AudioManagerInternal.class);
mAudioAttrs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).build();
}
@Override
public void setPlaybackToLocal(AudioAttributes attributes) {
boolean typeChanged;
synchronized (mLock) {
typeChanged = mVolumeType == PlaybackInfo.PLAYBACK_TYPE_REMOTE;
mVolumeType = PlaybackInfo.PLAYBACK_TYPE_LOCAL;
if (attributes != null) {
mAudioAttrs = attributes;
} else {
Log.e(TAG, "Received null audio attributes, using existing attributes");
}
}
if (typeChanged) {
final long token = Binder.clearCallingIdentity();
try {
mService.onSessionPlaybackTypeChanged(MediaSessionRecord.this);
} finally {
Binder.restoreCallingIdentity(token);
}
mHandler.post(MessageHandler.MSG_UPDATE_VOLUME);
}
}
public void playerAttributes(int piid, @NonNull AudioAttributes attr, int binderUid) {
final boolean change;
synchronized(mPlayerLock) {
final AudioPlaybackConfiguration apc = mPlayers.get(new Integer(piid));
if (checkConfigurationCaller(piid, apc, binderUid)) {
sEventLogger.log(new AudioAttrEvent(piid, attr));
change = apc.handleAudioAttributesEvent(attr);
} else {
Log.e(TAG, "Error updating audio attributes");
change = false;
}
}
if (change) {
dispatchPlaybackChange(false);
}
}
/**
* Return the volume ramp time expected before playback with the given AudioAttributes would
* start after gaining audio focus.
* @param attr attributes of the sound about to start playing
* @return time in ms
*/
protected static int getFocusRampTimeMs(int focusGain, AudioAttributes attr) {
switch (attr.getUsage()) {
case AudioAttributes.USAGE_MEDIA:
case AudioAttributes.USAGE_GAME:
return 1000;
case AudioAttributes.USAGE_ALARM:
case AudioAttributes.USAGE_NOTIFICATION_RINGTONE:
case AudioAttributes.USAGE_ASSISTANT:
case AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY:
case AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
return 700;
case AudioAttributes.USAGE_VOICE_COMMUNICATION:
case AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING:
case AudioAttributes.USAGE_NOTIFICATION:
case AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
case AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
case AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
case AudioAttributes.USAGE_NOTIFICATION_EVENT:
case AudioAttributes.USAGE_ASSISTANCE_SONIFICATION:
return 500;
case AudioAttributes.USAGE_UNKNOWN:
default:
return 0;
}
}
private AudioAttributes calculateAttributes() {
final Notification n = sbn.getNotification();
AudioAttributes attributes = getChannel().getAudioAttributes();
if (attributes == null) {
attributes = Notification.AUDIO_ATTRIBUTES_DEFAULT;
}
if (mPreChannelsNotification
&& (getChannel().getUserLockedFields()
& NotificationChannel.USER_LOCKED_SOUND) == 0) {
if (n.audioAttributes != null) {
// prefer audio attributes to stream type
attributes = n.audioAttributes;
} else if (n.audioStreamType >= 0
&& n.audioStreamType < AudioSystem.getNumStreamTypes()) {
// the stream type is valid, use it
attributes = new AudioAttributes.Builder()
.setInternalLegacyStreamType(n.audioStreamType)
.build();
} else if (n.audioStreamType != AudioSystem.STREAM_DEFAULT) {
Log.w(TAG, String.format("Invalid stream type: %d", n.audioStreamType));
}
}
return attributes;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private synchronized void createNotificationChannel() {
CharSequence name = MobiComKitConstants.PUSH_NOTIFICATION_NAME;
int importance = NotificationManager.IMPORTANCE_HIGH;
if (mNotificationManager != null && mNotificationManager.getNotificationChannel(MobiComKitConstants.AL_PUSH_NOTIFICATION) == null) {
NotificationChannel mChannel = new NotificationChannel(MobiComKitConstants.AL_PUSH_NOTIFICATION, name, importance);
mChannel.enableLights(true);
mChannel.setLightColor(Color.GREEN);
mChannel.setShowBadge(ApplozicClient.getInstance(context).isUnreadCountBadgeEnabled());
if (ApplozicClient.getInstance(context).getVibrationOnNotification()) {
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION).build();
mChannel.setSound(TextUtils.isEmpty(soundFilePath) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) : Uri.parse(soundFilePath), audioAttributes);
mNotificationManager.createNotificationChannel(mChannel);
Utils.printLog(context, TAG, "Created notification channel");
}
}
private int requestAudioFocus() {
int audioFocusResult;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioFocusResult = audioManager.requestAudioFocus(audioFocusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
} else {
if (audioFocusRequest == null) {
audioFocusRequest =
new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setOnAudioFocusChangeListener(audioFocusChangeListener)
.setWillPauseWhenDucked(true)
.setAudioAttributes(
new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
)
.build();
}
audioFocusResult = audioManager.requestAudioFocus(audioFocusRequest);
}
return audioFocusResult;
}
private void onStartSample() {
if (!isSamplePlaying()) {
if (mCallback != null) {
mCallback.onSampleStarting(this);
}
synchronized (this) {
if (mRingtone != null) {
try {
mRingtone.setAudioAttributes(new AudioAttributes.Builder(mRingtone
.getAudioAttributes())
.setFlags(AudioAttributes.FLAG_BYPASS_MUTE)
.build());
mRingtone.play();
} catch (Throwable e) {
Log.w(TAG, "Error playing ringtone, stream " + mStreamType, e);
}
}
}
}
}
private void createAlarmChannel(String uri) {
Log.e("KCA-A", "recv: " + uri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String soundKind = getStringPreferences(getApplicationContext(), PREF_KCA_NOTI_SOUND_KIND);
boolean isVibrate = soundKind.equals(getString(R.string.sound_kind_value_mixed)) || soundKind.equals(getString(R.string.sound_kind_value_vibrate));
notificationManager.deleteNotificationChannel(ALARM_CHANNEL_ID);
while (!alarmChannelList.isEmpty()) {
notificationManager.deleteNotificationChannel(alarmChannelList.poll());
}
AudioAttributes.Builder attrs = new AudioAttributes.Builder();
attrs.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION);
attrs.setUsage(AudioAttributes.USAGE_NOTIFICATION);
String channel_name = createAlarmId(uri, isVibrate);
alarmChannelList.add(channel_name);
NotificationChannel channel = new NotificationChannel(alarmChannelList.peek(),
getStringWithLocale(R.string.notification_appinfo_title), NotificationManager.IMPORTANCE_HIGH);
channel.setSound(Uri.parse(uri), attrs.build());
channel.enableVibration(isVibrate);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
}
}
public VideoView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mVideoWidth = 0;
mVideoHeight = 0;
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
mAudioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE).build();
getHolder().addCallback(mSHCallback);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
/**
* Call this method before use @startStream for streaming internal audio only.
*
* @param bitrate AAC in kb.
* @param sampleRate of audio in hz. Can be 8000, 16000, 22500, 32000, 44100.
* @param isStereo true if you want Stereo audio (2 audio channels), false if you want Mono audio
* (1 audio channel).
* @see AudioPlaybackCaptureConfiguration.Builder#Builder(MediaProjection)
*/
@RequiresApi(api = Build.VERSION_CODES.Q)
public boolean prepareInternalAudio(int bitrate, int sampleRate, boolean isStereo) {
if (mediaProjection == null) {
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
}
AudioPlaybackCaptureConfiguration config = new AudioPlaybackCaptureConfiguration
.Builder(mediaProjection)
.addMatchingUsage(AudioAttributes.USAGE_MEDIA)
.addMatchingUsage(AudioAttributes.USAGE_GAME)
.addMatchingUsage(AudioAttributes.USAGE_UNKNOWN)
.build();
microphoneManager.createInternalMicrophone(config, sampleRate, isStereo);
prepareAudioRtp(isStereo, sampleRate);
return audioEncoder.prepareAudioEncoder(bitrate, sampleRate, isStereo,
microphoneManager.getMaxInputSize());
}
public static void playNotificationSound(MediaPlayer mediaPlayer, Context context, Uri uri) {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
}
if (uri != null && !Uri.EMPTY.equals(uri)) {
mediaPlayer.setDataSource(context, uri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attr = new AudioAttributes.Builder()
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.build();
mediaPlayer.setAudioAttributes(attr);
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
}
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
e.printStackTrace();
}
}
public static void playNotificationSound(MediaPlayer mediaPlayer, Context context, Uri uri) {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
}
if (uri != null && !Uri.EMPTY.equals(uri)) {
mediaPlayer.setDataSource(context, uri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attr = new AudioAttributes.Builder()
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.build();
mediaPlayer.setAudioAttributes(attr);
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
}
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
e.printStackTrace();
}
}
private void requestAudioFocus() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
AudioFocusRequest focusRequest =
new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(
new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int i) {
}
})
.build();
audioManager.requestAudioFocus(focusRequest);
} else {
audioManager.requestAudioFocus(null, AudioManager.STREAM_VOICE_CALL,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
}
private AudioFocusRequest getAudioFocusRequest() {
AudioFocusRequest request = null;
AudioAttributes audioAttributes = null;
if (android.os.Build.VERSION.SDK_INT >= VERSION_CODES.O) {
audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.build();
request = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setWillPauseWhenDucked(true)
.setAudioAttributes(audioAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(audioFocusChangeListener)
.build();
}
return request;
}
/**
* Plays the sound. This will pass the SoundData instance to the provided
* [Alarmio](../Alarmio) class, which will store the currently playing sound
* until it is stopped or cancelled.
*
* @param alarmio The active Application instance.
*/
public void play(Alarmio alarmio) {
if (type.equals(TYPE_RINGTONE) && url.startsWith("content://")) {
if (ringtone == null) {
ringtone = RingtoneManager.getRingtone(alarmio, Uri.parse(url));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ringtone.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build());
}
}
alarmio.playRingtone(ringtone);
} else {
alarmio.playStream(url, type,
new com.google.android.exoplayer2.audio.AudioAttributes.Builder()
.setUsage(C.USAGE_ALARM)
.build());
}
}
private void createNotificationChannel() {
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mChannelID = mContext.getPackageName() + ".channel_01";
// The user-visible name of the channel.
CharSequence name = mContext.getString(R.string.channel_name);
// The user-visible description of the channel
String description = mContext.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(mChannelID, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(mVibratePattern);
mChannel.setSound(mSoundURI, (new AudioAttributes.Builder())
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build());
mNotificationManager.createNotificationChannel(mChannel);
}
/**
* More verbose version of {@link #createChannelFor(Context, Recipient)}.
*/
public static synchronized @Nullable String createChannelFor(@NonNull Context context,
@NonNull String channelId,
@NonNull String displayName,
@Nullable Uri messageSound,
boolean vibrationEnabled)
{
if (!supported()) {
return null;
}
NotificationChannel channel = new NotificationChannel(channelId, displayName, NotificationManager.IMPORTANCE_HIGH);
setLedPreference(channel, TextSecurePreferences.getNotificationLedColor(context));
channel.setGroup(CATEGORY_MESSAGES);
channel.enableVibration(vibrationEnabled);
if (messageSound != null) {
channel.setSound(messageSound, new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
.build());
}
NotificationManager notificationManager = ServiceUtil.getNotificationManager(context);
notificationManager.createNotificationChannel(channel);
return channelId;
}
/**
* This method is used to start ringing the phone.
*/
@TargetApi(21)
private void startRing() {
if (audio != null) {
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
audio.setStreamVolume(AudioManager.STREAM_RING, audio.getStreamMaxVolume(AudioManager.STREAM_RING),
AudioManager.FLAG_PLAY_SOUND);
defaultRingtoneUri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE);
if (defaultRingtoneUri != null) {
defaultRingtone = RingtoneManager.getRingtone(this, defaultRingtoneUri);
if (defaultRingtone != null) {
if (deviceInfo.getSdkVersion() >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attributes = new AudioAttributes.Builder().
setUsage(AudioAttributes.USAGE_NOTIFICATION).
setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).
build();
defaultRingtone.setAudioAttributes(attributes);
} else {
defaultRingtone.setStreamType(AudioManager.STREAM_NOTIFICATION);
}
defaultRingtone.play();
}
}
}
}
@TargetApi(21)
private static AudioTrack createAudioTrackOnLollipopOrHigher(
int sampleRateInHz, int channelConfig, int bufferSizeInBytes) {
Logging.d(TAG, "createAudioTrackOnLollipopOrHigher");
// TODO(henrika): use setPerformanceMode(int) with PERFORMANCE_MODE_LOW_LATENCY to control
// performance when Android O is supported. Add some logging in the mean time.
final int nativeOutputSampleRate =
AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_VOICE_CALL);
Logging.d(TAG, "nativeOutputSampleRate: " + nativeOutputSampleRate);
if (sampleRateInHz != nativeOutputSampleRate) {
Logging.w(TAG, "Unable to use fast mode since requested sample rate is not native");
}
if (usageAttribute != DEFAULT_USAGE) {
Logging.w(TAG, "A non default usage attribute is used: " + usageAttribute);
}
// Create an audio track where the audio usage is for VoIP and the content type is speech.
return new AudioTrack(
new AudioAttributes.Builder()
.setUsage(usageAttribute)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build(),
new AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(sampleRateInHz)
.setChannelMask(channelConfig)
.build(),
bufferSizeInBytes,
AudioTrack.MODE_STREAM,
AudioManager.AUDIO_SESSION_ID_GENERATE);
}
private void calibrationNotificationCreate(String title, String content, Intent intent, int notificationId) {
NotificationCompat.Builder mBuilder = notificationBuilder(title, content, intent);
mBuilder.setVibrate(vibratePattern);
mBuilder.setLights(0xff00ff00, 300, 1000);
if(calibration_override_silent) {
mBuilder.setSound(Uri.parse(calibration_notification_sound), AudioAttributes.USAGE_ALARM);
} else {
mBuilder.setSound(Uri.parse(calibration_notification_sound));
}
NotificationManager mNotifyMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
//mNotifyMgr.cancel(notificationId);
mNotifyMgr.notify(notificationId, mBuilder.build());
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void initFocusRequest() {
AudioAttributes mPlaybackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
mFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(mPlaybackAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(audioFocusChangeListener)
.build();
}
public boolean isNotification() {
switch (usageHint) {
case AudioAttributes.USAGE_NOTIFICATION:
case AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
case AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
case AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
return true;
default:
return false;
}
}
static private NotificationChannel updateNotificationChannel( Context context, NotificationChannel notificationChannel, final AndroidPushTemplate template )
{
if( template.getShowBadge() != null )
notificationChannel.setShowBadge( template.getShowBadge() );
if( template.getPriority() != null && template.getPriority() > 0 && template.getPriority() < 6 )
notificationChannel.setImportance( template.getPriority() ); // NotificationManager.IMPORTANCE_DEFAULT
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage( AudioAttributes.USAGE_NOTIFICATION_RINGTONE )
.setContentType( AudioAttributes.CONTENT_TYPE_SONIFICATION )
.setFlags( AudioAttributes.FLAG_AUDIBILITY_ENFORCED )
.setLegacyStreamType( AudioManager.STREAM_NOTIFICATION )
.build();
notificationChannel.setSound( PushTemplateHelper.getSoundUri( context, template.getSound() ), audioAttributes );
if (template.getLightsColor() != null)
{
notificationChannel.enableLights( true );
notificationChannel.setLightColor( template.getLightsColor()|0xFF000000 );
}
if( template.getVibrate() != null && template.getVibrate().length > 0 )
{
long[] vibrate = new long[ template.getVibrate().length ];
int index = 0;
for( long l : template.getVibrate() )
vibrate[ index++ ] = l;
notificationChannel.enableVibration( true );
notificationChannel.setVibrationPattern( vibrate );
}
return notificationChannel;
}
private void setVolumeTo(String packageName, int pid, int uid,
ISessionControllerCallback caller, int value, int flags) {
if (mVolumeType == PlaybackInfo.PLAYBACK_TYPE_LOCAL) {
int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs);
mAudioManagerInternal.setStreamVolumeForUid(stream, value, flags, packageName, uid);
} else {
if (mVolumeControlType != VolumeProvider.VOLUME_CONTROL_ABSOLUTE) {
// Nothing to do. The volume can't be set directly.
return;
}
value = Math.max(0, Math.min(value, mMaxVolume));
mSessionCb.setVolumeTo(packageName, pid, uid, caller, value);
int volumeBefore = (mOptimisticVolume < 0 ? mCurrentVolume : mOptimisticVolume);
mOptimisticVolume = Math.max(0, Math.min(value, mMaxVolume));
mHandler.removeCallbacks(mClearOptimisticVolumeRunnable);
mHandler.postDelayed(mClearOptimisticVolumeRunnable, OPTIMISTIC_VOLUME_TIMEOUT);
if (volumeBefore != mOptimisticVolume) {
pushVolumeUpdate();
}
mService.notifyRemoteVolumeChanged(flags, this);
if (DEBUG) {
Log.d(TAG, "Set optimistic volume to " + mOptimisticVolume + " max is "
+ mMaxVolume);
}
}
}
private void checkVolumeForPrivilegedAlarm(AudioPlaybackConfiguration apc, int event) {
if (event == AudioPlaybackConfiguration.PLAYER_STATE_STARTED ||
apc.getPlayerState() == AudioPlaybackConfiguration.PLAYER_STATE_STARTED) {
if ((apc.getAudioAttributes().getAllFlags() & FLAGS_FOR_SILENCE_OVERRIDE)
== FLAGS_FOR_SILENCE_OVERRIDE &&
apc.getAudioAttributes().getUsage() == AudioAttributes.USAGE_ALARM &&
mContext.checkPermission(android.Manifest.permission.MODIFY_PHONE_STATE,
apc.getClientPid(), apc.getClientUid()) ==
PackageManager.PERMISSION_GRANTED) {
if (event == AudioPlaybackConfiguration.PLAYER_STATE_STARTED &&
apc.getPlayerState() != AudioPlaybackConfiguration.PLAYER_STATE_STARTED) {
if (mPrivilegedAlarmActiveCount++ == 0) {
mSavedAlarmVolume = AudioSystem.getStreamVolumeIndex(
AudioSystem.STREAM_ALARM, AudioSystem.DEVICE_OUT_SPEAKER);
AudioSystem.setStreamVolumeIndex(AudioSystem.STREAM_ALARM,
mMaxAlarmVolume, AudioSystem.DEVICE_OUT_SPEAKER);
}
} else if (event != AudioPlaybackConfiguration.PLAYER_STATE_STARTED &&
apc.getPlayerState() == AudioPlaybackConfiguration.PLAYER_STATE_STARTED) {
if (--mPrivilegedAlarmActiveCount == 0) {
if (AudioSystem.getStreamVolumeIndex(
AudioSystem.STREAM_ALARM, AudioSystem.DEVICE_OUT_SPEAKER) ==
mMaxAlarmVolume) {
AudioSystem.setStreamVolumeIndex(AudioSystem.STREAM_ALARM,
mSavedAlarmVolume, AudioSystem.DEVICE_OUT_SPEAKER);
}
}
}
}
}
}
private void calibrationNotificationCreate(String title, String content, Intent intent, int notificationId) {
NotificationCompat.Builder mBuilder = notificationBuilder(title, content, intent);
mBuilder.setVibrate(vibratePattern);
mBuilder.setLights(0xff00ff00, 300, 1000);
if(calibration_override_silent) {
mBuilder.setSound(Uri.parse(calibration_notification_sound), AudioAttributes.USAGE_ALARM);
} else {
mBuilder.setSound(Uri.parse(calibration_notification_sound));
}
NotificationManager mNotifyMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
//mNotifyMgr.cancel(notificationId);
mNotifyMgr.notify(notificationId, mBuilder.build());
}
/**
* Sets the audio attributes to be used when speaking text or playing
* back a file.
*
* @param audioAttributes Valid AudioAttributes instance.
*
* @return {@link #ERROR} or {@link #SUCCESS}.
*/
public int setAudioAttributes(AudioAttributes audioAttributes) {
if (audioAttributes != null) {
synchronized (mStartLock) {
mParams.putParcelable(Engine.KEY_PARAM_AUDIO_ATTRIBUTES,
audioAttributes);
}
return SUCCESS;
}
return ERROR;
}
@Override
public void vibrate(int uid, String opPkg,
VibrationEffect effect, AudioAttributes attributes) {
if (mService == null) {
Log.w(TAG, "Failed to vibrate; no vibrator service.");
return;
}
try {
mService.vibrate(uid, opPkg, effect, usageForAttributes(attributes), mToken);
} catch (RemoteException e) {
Log.w(TAG, "Failed to vibrate.", e);
}
}