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:im.vector.activity.CallViewActivity.java

/**
 * Initialize the audio volume./*  www.  ja  va 2  s . c  o  m*/
 */
private void initMediaPlayerVolume() {
    AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

    // use the ringing volume to initialize the playing volume
    // it does not make sense to ring louder
    int maxVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    int minValue = firstCallAlert ? FIRST_PERCENT_VOLUME : DEFAULT_PERCENT_VOLUME;
    int ratio = (audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 100) / maxVol;

    firstCallAlert = false;

    // ensure there is a minimum audio level
    // some users could complain they did not hear their device was ringing.
    if (ratio < minValue) {
        setMediaPlayerVolume(minValue);
    } else {
        setMediaPlayerVolume(ratio);
    }
}

From source file:com.Beat.RingdroidEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    /* SongMetadataReader metadataReader = new SongMetadataReader(
    this, mFilename);/*from   ww  w. j a  va2s  .  com*/
     mTitle = metadataReader.mTitle;
     mArtist = metadataReader.mArtist;
     mAlbum = metadataReader.mAlbum;
     mYear = metadataReader.mYear;
     mGenre = metadataReader.mGenre;*/

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(RingdroidEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));
            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                RingdroidEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:im.vector.activity.CallViewActivity.java

private void setMediaPlayerVolume(int percent) {
    if (percent < 0 || percent > 100) {
        Log.e(LOG_TAG, "setMediaPlayerVolume percent is invalid: " + percent);
        return;//  w  ww . j a v a 2 s  .c  om
    }

    AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

    mCallVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);

    int maxMusicVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    int maxVoiceVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);

    if (maxMusicVol > 0) {
        int volume = (int) ((float) percent / 100f * maxMusicVol);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);

        volume = (int) ((float) percent / 100f * maxVoiceVol);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, volume, 0);
    }
    Log.i(LOG_TAG,
            "Set media volume (ringback) to: " + audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
}

From source file:net.nightwhistler.pageturner.fragment.ReadingFragment.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void registerRemoteControlClient(ComponentName componentName) {

    audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    Intent remoteControlIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    remoteControlIntent.setComponent(componentName);

    RemoteControlClient localRemoteControlClient = new RemoteControlClient(
            PendingIntent.getBroadcast(context, 0, remoteControlIntent, 0));

    localRemoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
            | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE);

    audioManager.registerRemoteControlClient(localRemoteControlClient);

    this.remoteControlClient = localRemoteControlClient;
}

From source file:com.morlunk.mumbleclient.app.PlumbleActivity.java

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (Settings.PREF_THEME.equals(key)) {
        // Recreate activity when theme is changed
        if (Build.VERSION.SDK_INT >= 11)
            recreate();// ww  w  .ja v a2s . c o m
        else {
            Intent intent = new Intent(this, PlumbleActivity.class);
            finish();
            startActivity(intent);
        }
    } else if (Settings.PREF_STAY_AWAKE.equals(key)) {
        setStayAwake(mSettings.shouldStayAwake());
    } else if (Settings.PREF_HANDSET_MODE.equals(key)) {
        setVolumeControlStream(
                mSettings.isHandsetMode() ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC);
    }
}

From source file:com.intel.xdk.player.Player.java

public void setAudioVolume(String volume) {
    //Valid volumes 0.0 to 1.0
    double castVol = Float.parseFloat(volume);
    if (castVol > 1.0)
        castVol = 1.0;//from   w w  w. ja va2  s.  c  o  m
    // Get the AudioManager
    AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
    int newVol = (int) (audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) * castVol);
    // Set the volume of played media to maximum.
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVol, 0);

    String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.player.audio.volume.set',true,true);document.dispatchEvent(e);";
    injectJS(js);
}

From source file:com.quran.labs.androidquran.service.AudioService.java

/**
 * Starts playing the next file.//from   ww  w .  j a  v a 2 s  .  c  om
 */
private void playAudio() {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
        String url = mAudioRequest == null ? null : mAudioRequest.getUrl();
        if (mAudioRequest == null || url == null) {
            Intent updateIntent = new Intent(AudioUpdateIntent.INTENT_NAME);
            updateIntent.putExtra(AudioUpdateIntent.STATUS, AudioUpdateIntent.STOPPED);
            mBroadcastManager.sendBroadcast(updateIntent);

            processStopRequest(true); // stop everything!
            return;
        }

        mIsStreaming = url.startsWith("http:") || url.startsWith("https:");
        if (!mIsStreaming) {
            File f = new File(url);
            if (!f.exists()) {
                Intent updateIntent = new Intent(AudioUpdateIntent.INTENT_NAME);
                updateIntent.putExtra(AudioUpdateIntent.STATUS, AudioUpdateIntent.STOPPED);
                updateIntent.putExtra(EXTRA_PLAY_INFO, mAudioRequest);
                mBroadcastManager.sendBroadcast(updateIntent);

                processStopRequest(true);
                return;
            }
        }

        Log.d(TAG, "okay, we are preparing to play - streaming is: " + mIsStreaming);
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(url);

        mAudioTitle = mAudioRequest.getTitle(getApplicationContext());

        mState = State.Preparing;
        setUpAsForeground(mAudioTitle);

        // Use the media button APIs (if available) to register ourselves
        // for media button events
        MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent);

        // starts preparing the media player in the background. When it's
        // done, it will call our OnPreparedListener (that is, the
        // onPrepared() method on this class, since we set the listener
        // to 'this').
        //
        // Until the media player is prepared, we *cannot* call start() on it!
        Log.d(TAG, "preparingAsync()...");
        mPlayer.prepareAsync();

        // If we are streaming from the internet, we want to hold a Wifi lock,
        // which prevents the Wifi radio from going to sleep while the song is
        // playing. If, on the other hand, we are *not* streaming, we want to
        // release the lock if we were holding it before.
        if (mIsStreaming) {
            mWifiLock.acquire();
        } else if (mWifiLock.isHeld()) {
            mWifiLock.release();
        }
    } catch (IOException ex) {
        Log.e(TAG, "IOException playing file: " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:org.connectbot.ConsoleFragment.java

@Override
public void onOptionsMenuClosed(Menu menu) {
    super.onOptionsMenuClosed(menu);

    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

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

/**
 * By Lin Date:2016/8/12  15:41/*from  w  w  w.j  a  v  a2  s.c  o  m*/
 *
 * @??
 */
private void onVolumeSlide(float percent) {

    if (mVolume == -1 && onScrollEnable) {
        return;
    }

    if (mVolume == -1) {
        mVolume = getAudioManager().getStreamVolume(AudioManager.STREAM_MUSIC);
        if (mVolume < 0)
            mVolume = 0;
        // 
    }
    int index = (int) (percent * mAudioMax) + mVolume;
    if (index > mAudioMax)
        index = mAudioMax;
    else if (index < 0)
        index = 0;
    // ?
    getAudioManager().setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

    //UI
    if (mMediaController != null) {
        mMediaController.showVolumeSet(index * 100 / mAudioMax);
    }

    onScrollEnable = true;
}

From source file:com.iamplus.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   www .j  a v a  2 s.  c  om*/
 */
void playNextSong(String manualUrl, Boolean userAction) {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
        MediaItem playingItem = null;
        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:");
        } else {
            mIsStreaming = false; // playing a locally available song

            playingItem = MusicRetriever.getInstance().getNextSong();
            if (playingItem == null) {

                MusicRetriever.getInstance().reset();
                playingItem = MusicRetriever.getInstance().getCurrentSong();

                if (!userAction) {
                    /**
                     * Pause playback if end of playlist
                     */
                    mPausePlayback = true;
                }
            }

            mCurrentPlayingItem = playingItem;
            // set the source of the media player a a content URI
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), playingItem.getURI());
        }

        // starts preparing the media player in the background. When it's done, it will call
        // our OnPreparedListener (that is, the onPrepared() method on this class, since we set
        // the listener to 'this').
        //
        // Until the media player is prepared, we *cannot* call start() on it!
        mPlayer.prepareAsync();

        // If we are streaming from the internet, we want to hold a Wifi lock, which prevents
        // the Wifi radio from going to sleep while the song is playing. If, on the other hand,
        // we are *not* streaming, we want to release the lock if we were holding it before.
        //         if (mIsStreaming) mWifiLock.acquire();
        //         else if (mWifiLock.isHeld()) mWifiLock.release();

        updateRemoteControlPlayingState();
    } catch (IOException ex) {
        Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
        ex.printStackTrace();
        Toast.makeText(getApplicationContext(), R.string.invalid_file_track, Toast.LENGTH_LONG).show();
        processStopRequest();
    }
}