Example usage for android.media AudioManager getStreamVolume

List of usage examples for android.media AudioManager getStreamVolume

Introduction

In this page you can find the example usage for android.media AudioManager getStreamVolume.

Prototype

public int getStreamVolume(int streamType) 

Source Link

Document

Returns the current volume index for a particular stream.

Usage

From source file:org.freelectron.leobel.testlwa.models.AVSAudioPlayer.java

public AVSAudioPlayer(AudioManager audioManager, AVSController controller) {
    this.audioManager = audioManager;
    this.controller = controller;
    resLoader = Thread.currentThread().getContextClassLoader();
    timer = new AudioPlayerTimer();
    waitForPlaybackFinished = false;/*from   w  w w . j  av a2 s .c o  m*/
    playQueue = new LinkedList<Stream>();
    speakQueue = new LinkedList<SpeakItem>();
    streamUrls = new HashSet<String>();
    attemptedUrls = new HashSet<String>();
    cachedAudioFiles = new HashMap<String, String>();
    setupAudioPlayer();

    currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    VOLUME_SCALAR = maxVolume / VOLUME_SCALAR;
    currentlyMuted = currentVolume == 0;

    audioPlayerStateMachine = new AudioPlayerStateMachine(this, controller);

    progressReporter = new AudioPlayerProgressReporter(
            new ProgressReportDelayEventRunnable(audioPlayerStateMachine),
            new ProgressReportIntervalEventRunnable(audioPlayerStateMachine), timer);

    listeners = new HashSet<>();
}

From source file:com.wso2.mobile.mdm.services.Operation.java

/**
 * Mute the device//  w  ww.  jav a 2  s .  c o m
 */
private void muteDevice() {
    Log.v("MUTING THE DEVICE : ", "MUTING");
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    Log.v("VOLUME : ", "" + audioManager.getStreamVolume(AudioManager.STREAM_RING));
    audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
    Log.v("VOLUME AFTER: ", "" + audioManager.getStreamVolume(AudioManager.STREAM_RING));

}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/**
 * Refresh the sound level bar on the main activity to reflect the current sound level
 * of the system./*w  w  w .  jav a  2  s  . com*/
 */
private void refreshSoundLevelBar() {
    mBarMasterLevel.setEnabled(true);
    AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
    mBarMasterLevel.setProgress(currentVolume);
}

From source file:com.speedtong.example.ui.chatting.ChattingActivity.java

private void initToneGenerator() {
    AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    if (mToneGenerator == null) {
        try {//from  w w  w . j  ava 2s  . c  o  m
            int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            int streamMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int volume = (int) (TONE_RELATIVE_VOLUME * (streamVolume / streamMaxVolume));
            mToneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, volume);

        } catch (RuntimeException e) {
            LogUtil.d("Exception caught while creating local tone generator: " + e);
            mToneGenerator = null;
        }
    }
}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/** Refresh the text on the main activity that shows the app states and audio settings. */
void refreshState() {
    log("refreshState!");

    //get current audio level
    AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
    mBarMasterLevel.setProgress(currentVolume);

    mTextViewCurrentLevel.setText(String.format("Sound Level: %d/%d", currentVolume, mBarMasterLevel.getMax()));

    log("refreshState 2b");

    // get info//w w w .j  a v a2  s  .  c  o m
    int samplingRate = getApp().getSamplingRate();
    int playerBuffer = getApp().getPlayerBufferSizeInBytes() / Constant.BYTES_PER_FRAME;
    int recorderBuffer = getApp().getRecorderBufferSizeInBytes() / Constant.BYTES_PER_FRAME;
    StringBuilder s = new StringBuilder(200);
    s.append("SR: " + samplingRate + " Hz");
    int audioThreadType = getApp().getAudioThreadType();
    switch (audioThreadType) {
    case Constant.AUDIO_THREAD_TYPE_JAVA:
        s.append(" Play Frames: " + playerBuffer);
        s.append(" Record Frames: " + recorderBuffer);
        s.append(" Audio: JAVA");
        break;
    case Constant.AUDIO_THREAD_TYPE_NATIVE:
        s.append(" Frames: " + playerBuffer);
        s.append(" Audio: NATIVE");
        break;
    }

    // mic source
    int micSource = getApp().getMicSource();
    String micSourceName = getApp().getMicSourceString(micSource);
    if (micSourceName != null) {
        s.append(String.format(" Mic: %s", micSourceName));
    }

    String info = getApp().getSystemInfo();
    s.append(" " + info);

    // show buffer test duration
    int bufferTestDuration = getApp().getBufferTestDuration();
    s.append("\nBuffer Test Duration: " + bufferTestDuration + "s");

    // show buffer test wave plot duration
    int bufferTestWavePlotDuration = getApp().getBufferTestWavePlotDuration();
    s.append("   Buffer Test Wave Plot Duration: last " + bufferTestWavePlotDuration + "s");

    mTextInfo.setText(s.toString());

    String estimatedLatency = "----";

    if (mCorrelation.mEstimatedLatencyMs > 0.0001) {
        estimatedLatency = String.format("%.2f ms", mCorrelation.mEstimatedLatencyMs);
    }

    mTextViewEstimatedLatency.setText(String.format("Latency: %s Confidence: %.2f", estimatedLatency,
            mCorrelation.mEstimatedLatencyConfidence));
}

From source file:com.ieeton.user.activity.ChatActivity.java

private void playSound() {
    AudioManager mAudioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    int curVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
    if (curVolume == 0) {
        return;//ww  w .  j a v a2  s . co m
    }

    mSoundPool.play(mSoundID, curVolume, curVolume, 0, 0, 1);
}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/** Save a .txt file of various test results. */
void saveReport(Uri uri) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    FileOutputStream outputStream;
    try {//from www .  ja va  2  s .  co m
        parcelFileDescriptor = getApplicationContext().getContentResolver().openFileDescriptor(uri, "w");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        outputStream = new FileOutputStream(fileDescriptor);

        log("Done creating output stream");

        String endline = "\n";
        final int stringLength = 300;
        StringBuilder sb = new StringBuilder(stringLength);
        sb.append("DateTime = " + mCurrentTime + endline);
        sb.append(INTENT_SAMPLING_FREQUENCY + " = " + getApp().getSamplingRate() + endline);
        sb.append(INTENT_RECORDER_BUFFER + " = "
                + getApp().getRecorderBufferSizeInBytes() / Constant.BYTES_PER_FRAME + endline);
        sb.append(INTENT_PLAYER_BUFFER + " = "
                + getApp().getPlayerBufferSizeInBytes() / Constant.BYTES_PER_FRAME + endline);
        sb.append(INTENT_AUDIO_THREAD + " = " + getApp().getAudioThreadType() + endline);
        int micSource = getApp().getMicSource();

        String audioType = "unknown";
        switch (getApp().getAudioThreadType()) {
        case Constant.AUDIO_THREAD_TYPE_JAVA:
            audioType = "JAVA";
            break;
        case Constant.AUDIO_THREAD_TYPE_NATIVE:
            audioType = "NATIVE";
            break;
        }
        sb.append(INTENT_AUDIO_THREAD + "_String = " + audioType + endline);

        sb.append(INTENT_MIC_SOURCE + " = " + micSource + endline);
        sb.append(INTENT_MIC_SOURCE + "_String = " + getApp().getMicSourceString(micSource) + endline);
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        sb.append(INTENT_AUDIO_LEVEL + " = " + currentVolume + endline);

        switch (mTestType) {
        case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_LATENCY:
            if (mCorrelation.mEstimatedLatencyMs > 0.0001) {
                sb.append(String.format("LatencyMs = %.2f", mCorrelation.mEstimatedLatencyMs) + endline);
            } else {
                sb.append(String.format("LatencyMs = unknown") + endline);
            }

            sb.append(String.format("LatencyConfidence = %.2f", mCorrelation.mEstimatedLatencyConfidence)
                    + endline);
            break;
        case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_BUFFER_PERIOD:
            sb.append("Buffer Test Duration (s) = " + mBufferTestDuration + endline);

            // report expected recorder buffer period
            int expectedRecorderBufferPeriod = mRecorderBufferSizeInBytes / Constant.BYTES_PER_FRAME
                    * Constant.MILLIS_PER_SECOND / mSamplingRate;
            sb.append("Expected Recorder Buffer Period (ms) = " + expectedRecorderBufferPeriod + endline);

            // report recorder results
            int recorderBufferSize = mRecorderBufferSizeInBytes / Constant.BYTES_PER_FRAME;
            int[] recorderBufferData = null;
            int recorderBufferDataMax = 0;
            switch (mAudioThreadType) {
            case Constant.AUDIO_THREAD_TYPE_JAVA:
                recorderBufferData = mRecorderBufferPeriod.getBufferPeriodArray();
                recorderBufferDataMax = mRecorderBufferPeriod.getMaxBufferPeriod();
                break;
            case Constant.AUDIO_THREAD_TYPE_NATIVE:
                recorderBufferData = mNativeRecorderBufferPeriodArray;
                recorderBufferDataMax = mNativeRecorderMaxBufferPeriod;
                break;
            }
            if (recorderBufferData != null) {
                // this is the range of data that actually has values
                int usefulDataRange = Math.min(recorderBufferDataMax + 1, recorderBufferData.length);
                int[] usefulBufferData = Arrays.copyOfRange(recorderBufferData, 0, usefulDataRange);
                PerformanceMeasurement measurement = new PerformanceMeasurement(recorderBufferSize,
                        mSamplingRate, usefulBufferData);
                boolean isBufferSizesMismatch = measurement.determineIsBufferSizesMatch();
                double benchmark = measurement.computeWeightedBenchmark();
                int outliers = measurement.countOutliers();
                sb.append("Recorder Buffer Sizes Mismatch = " + isBufferSizesMismatch + endline);
                sb.append("Recorder Benchmark = " + benchmark + endline);
                sb.append("Recorder Number of Outliers = " + outliers + endline);
            } else {
                sb.append("Cannot Find Recorder Buffer Period Data!" + endline);
            }

            // report player results
            int playerBufferSize = mPlayerBufferSizeInBytes / Constant.BYTES_PER_FRAME;
            int[] playerBufferData = null;
            int playerBufferDataMax = 0;
            switch (mAudioThreadType) {
            case Constant.AUDIO_THREAD_TYPE_JAVA:
                playerBufferData = mPlayerBufferPeriod.getBufferPeriodArray();
                playerBufferDataMax = mPlayerBufferPeriod.getMaxBufferPeriod();
                break;
            case Constant.AUDIO_THREAD_TYPE_NATIVE:
                playerBufferData = mNativePlayerBufferPeriodArray;
                playerBufferDataMax = mNativePlayerMaxBufferPeriod;
                break;
            }
            if (playerBufferData != null) {
                // this is the range of data that actually has values
                int usefulDataRange = Math.min(playerBufferDataMax + 1, playerBufferData.length);
                int[] usefulBufferData = Arrays.copyOfRange(playerBufferData, 0, usefulDataRange);
                PerformanceMeasurement measurement = new PerformanceMeasurement(playerBufferSize, mSamplingRate,
                        usefulBufferData);
                boolean isBufferSizesMismatch = measurement.determineIsBufferSizesMatch();
                double benchmark = measurement.computeWeightedBenchmark();
                int outliers = measurement.countOutliers();
                sb.append("Player Buffer Sizes Mismatch = " + isBufferSizesMismatch + endline);
                sb.append("Player Benchmark = " + benchmark + endline);
                sb.append("Player Number of Outliers = " + outliers + endline);

            } else {
                sb.append("Cannot Find Player Buffer Period Data!" + endline);
            }

            // report expected player buffer period
            int expectedPlayerBufferPeriod = mPlayerBufferSizeInBytes / Constant.BYTES_PER_FRAME
                    * Constant.MILLIS_PER_SECOND / mSamplingRate;
            if (audioType.equals("JAVA")) {
                // javaPlayerMultiple depends on the samples written per AudioTrack.write()
                int javaPlayerMultiple = 2;
                expectedPlayerBufferPeriod *= javaPlayerMultiple;
            }
            sb.append("Expected Player Buffer Period (ms) = " + expectedPlayerBufferPeriod + endline);

            // report estimated number of glitches
            int numberOfGlitches = estimateNumberOfGlitches(mGlitchesData);
            sb.append("Estimated Number of Glitches = " + numberOfGlitches + endline);

            // report if the total glitching interval is too long
            sb.append("Total glitching interval too long: " + mGlitchingIntervalTooLong + endline);
        }

        String info = getApp().getSystemInfo();
        sb.append("SystemInfo = " + info + endline);

        outputStream.write(sb.toString().getBytes());
        parcelFileDescriptor.close();
    } catch (Exception e) {
        log("Failed to open text file " + e);
    } finally {
        try {
            if (parcelFileDescriptor != null) {
                parcelFileDescriptor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("Error closing ParcelFile Descriptor");
        }
    }

}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * ?.//from w w w. ja v  a2s  .  co m
 * 
 * @param status 
 */
public void sendOnStatusChangeEvent(final String status) {

    if (onStatusChangeEventFlag) {
        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, MediaPlayerProfile.PROFILE_NAME,
                null, MediaPlayerProfile.ATTRIBUTE_ON_STATUS_CHANGE);

        AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);

        double maxVolume = 1;
        double mVolume = 0;

        mVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
        maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        double mVolumeValue = mVolume / maxVolume;

        for (int i = 0; i < events.size(); i++) {

            Event event = events.get(i);
            Intent intent = EventManager.createEventMessage(event);

            MediaPlayerProfile.setAttribute(intent, MediaPlayerProfile.ATTRIBUTE_ON_STATUS_CHANGE);
            Bundle mediaPlayer = new Bundle();
            MediaPlayerProfile.setStatus(mediaPlayer, status);
            MediaPlayerProfile.setMediaId(mediaPlayer, myCurrentFilePath);
            MediaPlayerProfile.setMIMEType(mediaPlayer, myCurrentFileMIMEType);
            MediaPlayerProfile.setPos(mediaPlayer, myCurrentMediaPosition);
            MediaPlayerProfile.setVolume(mediaPlayer, mVolumeValue);
            MediaPlayerProfile.setMediaPlayer(intent, mediaPlayer);
            getContext().sendBroadcast(intent);
        }
    }
}

From source file:com.PPRZonDroid.MainActivity.java

/**
 * Play warning sound if airspeed goes below the selected value
 *
 * @param context/*w ww.j a va2  s  .  c  om*/
 * @throws IllegalArgumentException
 * @throws SecurityException
 * @throws IllegalStateException
 * @throws IOException
 */
public void play_sound(Context context)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {

    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    MediaPlayer mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(context, soundUri);
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    //Set volume max!!!
    audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,
            audioManager.getStreamMaxVolume(audioManager.STREAM_SYSTEM), 0);

    if (audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

private void setStreamVolume() {
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    if (volume != 0) {
        debug("setStreamVolume:" + volume);
        Log.d("ChatActivity", "The volume changed and saved to : " + volume);
        MainActivity.volume = volume;//from  ww  w.  j a  v a2  s.  c o m
    }
}