android.media.AudioAttributes Java Examples

The following examples show how to use android.media.AudioAttributes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AndroidAudioPlayer.java    From Android-Guitar-Tuner with Apache License 2.0 10 votes vote down vote up
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();
}
 
Example #2
Source File: AppRTCAudioManager.java    From sealrtc-android with MIT License 7 votes vote down vote up
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;
}
 
Example #3
Source File: TwilioVideoActivity.java    From cordova-plugin-twilio-video with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #4
Source File: MediaSessionRecord.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #5
Source File: KcaAlarmService.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #6
Source File: DisplayBase.java    From rtmp-rtsp-stream-client-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #7
Source File: MediaFocusControl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #8
Source File: MediaSessionRecord.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #9
Source File: SeekBarVolumizer.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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);
                }
            }
        }
    }
}
 
Example #10
Source File: KcaUtils.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
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();
    }
}
 
Example #11
Source File: KcaUtils.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
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();
    }
}
 
Example #12
Source File: PlaybackActivityMonitor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #13
Source File: VideoView.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: NotificationRecord.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: TtsService.java    From android-app with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: NotificationChannels.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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");
    }
}
 
Example #17
Source File: SoundData.java    From Alarmio with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example #18
Source File: AudioFocusManager.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.O)
private void initFocusRequest() {
    AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build();
    mFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
            .setAudioAttributes(audioAttributes)
            .setAcceptsDelayedFocusGain(true)
            .setOnAudioFocusChangeListener(this)
            .build();
}
 
Example #19
Source File: soundPlayer.java    From Game with GNU General Public License v3.0 5 votes vote down vote up
public static void playSoundFile(String key) {
    try {
        if (!orsc.mudclient.optionSoundDisabled) {
            File sound = orsc.mudclient.soundCache.get(key + ".wav");
            if (sound == null)
                return;
            try {
                MediaPlayer player = new MediaPlayer();
                AudioAttributes audioAttrib = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .build();
                player.setDataSource(sound.getPath());
                player.setAudioAttributes(audioAttrib);
                player.setLooping(false);
                player.prepare();
                player.start();
                player.setOnCompletionListener(MediaPlayer::release);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    } catch (RuntimeException ignored) {
    }
}
 
Example #20
Source File: NotificationChannelCompat.java    From notification-channel-compat with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the sound that should be played for notifications posted to this channel and its
 * audio attributes. Notification channels with an {@link #getImportance() importance} of at
 * least {@link NotificationManager#IMPORTANCE_DEFAULT} should have a sound.
 * <p>
 * Only modifiable before the channel is submitted to
 * {NotificationManager#createNotificationChannelCompat(NotificationChannelCompat)}.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void setSound(Uri sound, AudioAttributes audioAttributes) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        _oreoNotificationChannel.setSound(sound, audioAttributes);
        return;
    }
    this.mSound = sound;
    this.mAudioAttributes = audioAttributes;
    // do not override mAudioStreamType as it may be set for earlier sdk
}
 
Example #21
Source File: Manager.java    From cordova-plugin-firebase-extended-notification with MIT License 5 votes vote down vote up
private void createNotificationChannel(Options options) {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        if(options.doesHeadsUp()) {
            importance = NotificationManager.IMPORTANCE_HIGH;
        } else if(!options.doesSound()) {
            importance = NotificationManager.IMPORTANCE_LOW;
        }
        NotificationChannel channel = new NotificationChannel(options.getChannelId(), options.getChannelName(), importance);
        if(options.doesHeadsUp()) {
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        }
        channel.setDescription(options.getChannelDescription());
        if(options.doesSound() && options.getSoundUri() != null) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setLegacyStreamType(android.media.AudioManager.STREAM_NOTIFICATION)
                    .build();
            channel.setSound(options.getSoundUri(), audioAttributes);
        }
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = this.context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}
 
Example #22
Source File: SimpleAudioOutput.java    From android-midisuite with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
protected AudioTrack createAudioTrack() {
    AudioAttributes.Builder attributesBuilder = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC);
    boolean doLowLatency = (AudioLatencyTuner.isLowLatencySupported()
            && mLatencyController.isLowLatencyEnabled());
    if (doLowLatency) {
        Log.i(TAG, "createAudioTrack() using FLAG_LOW_LATENCY");
        attributesBuilder.setFlags(AudioLatencyTuner.getLowLatencyFlag());
    }
    AudioAttributes attributes = attributesBuilder.build();

    AudioFormat format = new AudioFormat.Builder()
            .setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
            .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
            .build();
    AudioTrack.Builder builder = new AudioTrack.Builder()
            .setAudioAttributes(attributes)
            .setAudioFormat(format);
    if (doLowLatency) {
        // Start with a bigger buffer because we can lower it later.
        int bufferSizeInFrames = LOW_LATENCY_BUFFER_CAPACITY_IN_FRAMES;
        builder.setBufferSizeInBytes(bufferSizeInFrames * BYTES_PER_FRAME);
    }
    AudioTrack track = builder.build();
    if (track == null) {
        throw new RuntimeException("Could not make the Audio Track! attributes = "
                + attributes + ", format = " + format);
    }
    return track;
}
 
Example #23
Source File: Main.java    From Simple-Brick-Games with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected void createNewSoundPool() {
    AudioAttributes attributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_GAME)
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .build();
    sp = new SoundPool.Builder()
            .setAudioAttributes(attributes)
            .build();
}
 
Example #24
Source File: Notifications.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
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());
}
 
Example #25
Source File: SoundPoolBuilder.java    From soundboard with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static SoundPool buildModern() {
    AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_GAME)
            .build();
    return new SoundPool.Builder()
            .setMaxStreams(2)
            .setAudioAttributes(audioAttributes)
            .build();
}
 
Example #26
Source File: AdamantLocalMessagingService.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
private String buildChannel() {
    String channelId = "";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String channelName = getString(R.string.adamant_default_notification_channel);

        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        NotificationChannel chan = new NotificationChannel(ADAMANT_DEFAULT_NOTIFICATION_CHANNEL_ID,
                channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.RED);
        chan.enableLights(true);
        chan.enableVibration(true);
        chan.setVibrationPattern(NotificationHelper.VIBRATE_PATTERN);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        chan.setSound(NotificationHelper.SOUND_URI, attributes);

        NotificationManager service = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        if (service != null) {
            service.createNotificationChannel(chan);
            channelId = ADAMANT_DEFAULT_NOTIFICATION_CHANNEL_ID;
        }
    }

    return channelId;
}
 
Example #27
Source File: NotificationChannel.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static AudioAttributes safeAudioAttributes(XmlPullParser parser) {
    int usage = safeInt(parser, ATT_USAGE, AudioAttributes.USAGE_NOTIFICATION);
    int contentType = safeInt(parser, ATT_CONTENT_TYPE,
            AudioAttributes.CONTENT_TYPE_SONIFICATION);
    int flags = safeInt(parser, ATT_FLAGS, 0);
    return new AudioAttributes.Builder()
            .setUsage(usage)
            .setContentType(contentType)
            .setFlags(flags)
            .build();
}
 
Example #28
Source File: CustomDeviceActivity.java    From voice-quickstart-android with MIT License 5 votes vote down vote up
private void setAudioFocus(boolean setFocus) {
    if (audioManager != null) {
        if (setFocus) {
            savedAudioMode = audioManager.getMode();
            // Request audio focus before making any device switch.
            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(i -> {
                        })
                        .build();
                audioManager.requestAudioFocus(focusRequest);
            } else {
                audioManager.requestAudioFocus(
                        focusChange -> {
                        },
                        AudioManager.STREAM_VOICE_CALL,
                        AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            }
            /*
             * Start by setting MODE_IN_COMMUNICATION as default audio mode. It is
             * required to be in this mode when playout and/or recording starts for
             * best possible VoIP performance. Some devices have difficulties with speaker mode
             * if this is not set.
             */
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        } else {
            audioManager.setMode(savedAudioMode);
            audioManager.abandonAudioFocus(null);
        }
    }
}
 
Example #29
Source File: SystemVibrator.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #30
Source File: TextToSpeech.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}