Example usage for android.media AudioManager STREAM_MUSIC

List of usage examples for android.media AudioManager STREAM_MUSIC

Introduction

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

Prototype

int STREAM_MUSIC

To view the source code for android.media AudioManager STREAM_MUSIC.

Click Source Link

Document

Used to identify the volume of audio streams for music playback

Usage

From source file:com.xnxs.mediaplayer.widget.media.VRVideoView.java

private AudioManager getAudioManager() {
    if (mAudioManager == null) {
        mAudioManager = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
        mAudioMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    }//from  w  w w  .  j a  v a 2s  .c o  m
    return mAudioManager;
}

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

/**
 * ?./* w w w  .ja va2  s  .  com*/
 * 
 * @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.kiandastream.musicplayer.MusicService.java

/**
 * Starts playing the next song. If manualUrl is null, the next song will be randomly selected
 * from our Media Retriever (that is, it will be a random song in the user's device). If
 * manualUrl is non-null, then it specifies the URL or path to the song that will be played
 * next./*from  w  w w  .j av a2 s  .  c  o  m*/
 */
void playNextSong(String manualUrl) {
    mState = State.Stopped;
    //relaxResources(false); // release everything except MediaPlayer

    try {
        // MusicRetriever.Item playingItem = null;
        if (mPlayer != null)
            mPlayer.reset();

        if (manualUrl != null) {
            // set the source of the media player to a manual URL or path
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(manualUrl);
            mIsStreaming = manualUrl.startsWith("http:") || manualUrl.startsWith("https:");
            mState = State.Preparing;

            mPlayer.prepareAsync();
            mWifiLock.acquire();
            //  mPlayer.start();
            //  playingItem = new MusicRetriever.Item(0, null, manualUrl, null, 0);
        }

    } catch (IOException ex) {
        Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:github.daneren2005.dsub.util.Util.java

@TargetApi(8)
public static void requestAudioFocus(final Context context) {
    if (Build.VERSION.SDK_INT >= 8 && !hasFocus) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        hasFocus = true;/*  w  w  w.jav  a 2s  . c  o m*/
        audioManager.requestAudioFocus(new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                DownloadServiceImpl downloadService = (DownloadServiceImpl) context;
                if ((focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                        || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)
                        && !downloadService.isJukeboxEnabled()) {
                    if (downloadService.getPlayerState() == PlayerState.STARTED) {
                        SharedPreferences prefs = getPreferences(context);
                        int lossPref = Integer
                                .parseInt(prefs.getString(Constants.PREFERENCES_KEY_TEMP_LOSS, "1"));
                        if (lossPref == 2 || (lossPref == 1
                                && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
                            lowerFocus = true;
                            downloadService.setVolume(0.1f);
                        } else if (lossPref == 0
                                || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
                            pauseFocus = true;
                            downloadService.pause();
                        }
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    if (pauseFocus) {
                        pauseFocus = false;
                        downloadService.start();
                    } else if (lowerFocus) {
                        lowerFocus = false;
                        downloadService.setVolume(1.0f);
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS && !downloadService.isJukeboxEnabled()) {
                    hasFocus = false;
                    downloadService.pause();
                    audioManager.abandonAudioFocus(this);
                }
            }
        }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

protected void setVolume(int newVolume) {
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audio.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
    if (LOCAL_LOGV)
        log("volume set:" + String.valueOf(audio.getStreamVolume(AudioManager.STREAM_MUSIC)), "v");
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java

/**
 * Starts playback of a previously opened file.
 *//*w w w.j a v  a 2  s .  c om*/
public void play() {
    mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioManager.registerMediaButtonEventReceiver(
            new ComponentName(this.getPackageName(), MediaButtonIntentReceiver.class.getName()));

    if (mPlayer.isInitialized()) {
        // if we are at the end of the song, go to the next song first
        long duration = mPlayer.duration();
        if (mRepeatMode != REPEAT_CURRENT && duration > 2000 && mPlayer.position() >= duration - 2000) {
            gotoNext(true);
        }

        mPlayer.start();
        // make sure we fade in, in case a previous fadein was stopped because
        // of another focus loss
        mMediaplayerHandler.removeMessages(FADEDOWN);
        mMediaplayerHandler.sendEmptyMessage(FADEUP);

        updateNotification();
        if (!mIsSupposedToBePlaying) {
            mIsSupposedToBePlaying = true;
            notifyChange(PLAYSTATE_CHANGED);
        }

    } else if (mPlayListLen <= 0) {
        // This is mostly so that if you press 'play' on a bluetooth headset
        // without every having played anything before, it will still play
        // something.
        setShuffleMode(SHUFFLE_AUTO);
    }
}

From source file:com.devbrackets.android.playlistcore.service.PlaylistServiceCore.java

/**
 * Initializes the audio player./* w w w.  j  a  va 2 s.  c  om*/
 * If the audio player has already been initialized, then it will
 * be reset to prepare for the next playback item.
 */
protected void initializeAudioPlayer() {
    if (audioPlayer != null) {
        audioPlayer.reset();
        return;
    }

    audioPlayer = getNewAudioPlayer();
    audioPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    audioPlayer.setStreamType(AudioManager.STREAM_MUSIC);

    //Sets the listeners
    audioPlayer.setOnMediaPreparedListener(mediaListener);
    audioPlayer.setOnMediaCompletionListener(mediaListener);
    audioPlayer.setOnMediaErrorListener(mediaListener);
    audioPlayer.setOnMediaSeekCompletionListener(mediaListener);
    audioPlayer.setOnMediaBufferUpdateListener(mediaListener);
}

From source file:com.kjsaw.alcosys.ibacapp.IBAC.java

private void initBeepSound() {
    if (mediaPlayerBeep == null) {
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayerBeep = new MediaPlayer();
        mediaPlayerBeep.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayerBeep.setOnCompletionListener(beepListener);

        AssetFileDescriptor fileBeep = getResources().openRawResourceFd(R.raw.beep);
        try {//  w ww.  j a  v a2s .  com
            mediaPlayerBeep.setDataSource(fileBeep.getFileDescriptor(), fileBeep.getStartOffset(),
                    fileBeep.getLength());
            fileBeep.close();
            mediaPlayerBeep.setVolume(BEEP_VOLUME, BEEP_VOLUME);
            mediaPlayerBeep.prepare();
        } catch (IOException e) {
            mediaPlayerBeep = null;
        }
    }
}

From source file:com.kjsaw.alcosys.ibacapp.IBAC.java

private void initCaptureSound() {
    if (mediaPlayerCapture == null) {
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayerCapture = new MediaPlayer();
        mediaPlayerCapture.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayerCapture.setOnCompletionListener(captureListener);

        AssetFileDescriptor fileBeep = getResources().openRawResourceFd(R.raw.camera_flash);
        try {// ww  w .j a  v  a  2s.co m
            mediaPlayerCapture.setDataSource(fileBeep.getFileDescriptor(), fileBeep.getStartOffset(),
                    fileBeep.getLength());
            fileBeep.close();
            mediaPlayerCapture.setVolume(CAPTURE_VOLUME, CAPTURE_VOLUME);
            mediaPlayerCapture.prepare();
        } catch (IOException e) {
            mediaPlayerCapture = 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  ww. j a v a  2  s.co  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));
}