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.soubw.other.WaveformFragment.java

protected void loadFromFile() {
    mFile = new File(mFilename);
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;/*from  w  w w  . j a  v a2  s  .  co  m*/
    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        @Override
        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
    new Thread() {
        public void run() {
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Log.e(TAG, "Error while creating media player", e);
            }
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);
            } catch (final Exception e) {
                Log.e(TAG, "Error while loading sound file", e);
                mProgressDialog.dismiss();
                mInfo.setText(e.toString());
                return;
            }
            if (mLoadingKeepGoing) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        finishOpeningSoundFile();
                    }
                });
            }
        }
    }.start();
}

From source file:be.ugent.zeus.hydra.util.audiostream.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 ww  .  j av a2s.  com
 */
void playmp3(String mp3url) {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
        // set the source of the media player to a manual URL or path
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(mp3url);
        mIsStreaming = true;

        mSongTitle = "Urgent.fm";

        mState = State.Preparing;
        setUpAsForeground(mSongTitle + " (loading)");

        // Use the media button APIs (if available) to register ourselves for media button
        // events

        MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent);

        // Use the remote control APIs (if available) to set the playback state

        if (mRemoteControlClientCompat == null) {
            Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            intent.setComponent(mMediaButtonReceiverComponent);
            mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent.getBroadcast(
                    this /*context*/, 0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/));
            RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
        }

        mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);

        mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP);

        // Update the remote controls
        mRemoteControlClientCompat.editMetadata(true)
                .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, "Urgent.fm")
                .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt)
                .apply();

        // 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();
        }
    } catch (IOException ex) {
        Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

private boolean dispatchCenterWrapperTouchEvent(MotionEvent event) {
    Log.d(TAG, "dispatchCenterWrapperTouchEvent " + event);

    WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);

    DisplayMetrics screen = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(screen);

    if (mSurfaceYDisplayRange == 0) {
        mSurfaceYDisplayRange = Math.min(screen.widthPixels, screen.heightPixels);
    }//from   www .j  a v a2  s  .  c o m

    float x_changed, y_changed;
    if (touchX != -1f && touchY != -1f) {
        y_changed = event.getRawY() - touchY;
        x_changed = event.getRawX() - touchX;
    } else {
        x_changed = 0f;
        y_changed = 0f;
    }

    //        Log.e("tag","x_c=" + x_changed + "screen_x =" + screen.xdpi +" screen_rawx" + event.getRawX());
    float coef = Math.abs(y_changed / x_changed);
    float xgesturesize = (((event.getRawX() - touchX) / screen.xdpi) * 2.54f);//2.54f

    float delta_y = Math.max(1f, (Math.abs(mInitTouchY - event.getRawY()) / screen.xdpi + 0.5f) * 2f);

    switch (event.getAction()) {

    case MotionEvent.ACTION_DOWN:
        mTouchAction = TOUCH_NONE;
        touchX = event.getRawX();
        mVol = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        touchY = mInitTouchY = event.getRawY();
        break;

    case MotionEvent.ACTION_MOVE:

        if (mTouchAction != TOUCH_SEEK && coef > 2) {
            if (Math.abs(y_changed / mSurfaceYDisplayRange) < 0.05) {
                return false;
            }

            touchX = event.getRawX();
            touchY = event.getRawY();

            if (activity == null) {
                if ((int) touchX > (4 * screen.widthPixels / 7)) {
                    doVolumeTouch(y_changed);
                    //                        hideCenterInfo();
                    //                            hideOverlay(true);
                }
                // Brightness (Up or Down - Left side)
                if ((int) touchX < (3 * screen.widthPixels / 7)) {
                    doBrightnessTouch(y_changed);
                }
            } else {
                if (!activity.swap && activity.left.getVisibility() == View.VISIBLE
                        && activity.right.getVisibility() == View.VISIBLE) {
                    if ((int) touchX > (3 * screen.widthPixels / 4)) {
                        doVolumeTouch(y_changed);
                        //                        hideCenterInfo();
                        //                            hideOverlay(true);
                    }
                    // Brightness (Up or Down - Left side)
                    else if ((int) touchX >= (2 * screen.widthPixels / 4)) {
                        doBrightnessTouch(y_changed);
                    }
                } else {
                    if ((int) touchX < (1 * screen.widthPixels / 4)) {
                        doBrightnessTouch(y_changed);
                        //                        hideCenterInfo();
                        //                            hideOverlay(true);
                    }
                    // Brightness (Up or Down - Left side)
                    else if ((int) touchX < (2 * screen.widthPixels / 4)) {
                        doVolumeTouch(y_changed);
                    }
                }
            }

        } else {
            doSeekTouch(Math.round(delta_y), xgesturesize, false);
        }

        break;

    case MotionEvent.ACTION_UP:
        if (mTouchAction == TOUCH_SEEK) {
            doSeekTouch(Math.round(delta_y), xgesturesize, true);
        }

        if (mTouchAction != TOUCH_NONE) {
            hideCenterInfo();
        }

        touchX = -1f;
        touchY = -1f;
        break;
    default:
        break;
    }

    return mTouchAction != TOUCH_NONE;
}

From source file:com.example.android.mediarouter.player.MainActivity.java

private void registerRemoteControlClient() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Create the RCC and register with AudioManager and MediaRouter
        mAudioManager.requestAudioFocus(mAfChangeListener, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        mAudioManager.registerMediaButtonEventReceiver(mEventReceiver);
        mRemoteControlClient = new RemoteControlClient(mMediaPendingIntent);
        mAudioManager.registerRemoteControlClient(mRemoteControlClient);
        mMediaRouter.addRemoteControlClient(mRemoteControlClient);
        SampleMediaButtonReceiver.setActivity(MainActivity.this);
        mRemoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE);
        mRemoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
    }/* w  w  w. j a v  a 2s .c  o m*/
}

From source file:com.dzt.musicplay.player.AudioService.java

@TargetApi(Build.VERSION_CODES.FROYO)
private void changeAudioFocus(boolean gain) {
    if (!LibVlcUtil.isFroyoOrLater()) // NOP if not supported
        return;//from w  w w  . ja v  a  2  s . c  om

    if (audioFocusListener == null) {
        audioFocusListener = new OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {
                LibVLC libVLC = LibVLC.getExistingInstance();
                switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    if (libVLC.isPlaying())
                        libVLC.pause();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    /*
                     * Lower the volume to 36% to "duck" when an alert or
                     * something needs to be played.
                     */
                    libVLC.setVolume(36);
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                    libVLC.setVolume(100);
                    break;
                }
            }
        };
    }

    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (gain)
        am.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    else
        am.abandonAudioFocus(audioFocusListener);

}

From source file:com.example.android.mediarouter.player.RadioActivity.java

private void registerRemoteControlClient() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Create the RCC and register with AudioManager and MediaRouter
        mAudioManager.requestAudioFocus(mAfChangeListener, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        mAudioManager.registerMediaButtonEventReceiver(mEventReceiver);
        mRemoteControlClient = new RemoteControlClient(mMediaPendingIntent);
        mAudioManager.registerRemoteControlClient(mRemoteControlClient);
        mMediaRouter.addRemoteControlClient(mRemoteControlClient);
        SampleRadioButtonReceiver.setActivity(RadioActivity.this);
        mRemoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE);
        mRemoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
    }//from   w w  w . j  av  a  2 s  . c  om
}

From source file:com.namelessdev.mpdroid.NotificationService.java

/**
 * We try to get audio focus, but don't really try too hard.
 * We just want the lock screen cover art.
 *//*from ww w . j a  v  a2  s . c  o m*/
private void tryToGetAudioFocus() {
    if ((!app.getApplicationState().streamingMode || StreamingService.isWoundDown()) && !isAudioFocusedOnThis) {
        Log.d(TAG, "requesting audio focus");
        final int result = mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);

        isAudioFocusedOnThis = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
    }
}

From source file:com.teocci.utubinbg.BackgroundAudioService.java

/**
 * Extracts link from youtube video ID, so mediaPlayer can play it
 *///from  w  w w .ja v  a  2 s. c  o m
private void extractUrlAndPlay() {
    final String youtubeLink = "http://youtube.com/watch?v=" + videoItem.getId();
    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
        @Override
        public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
            if (ytFiles != null) {
                YtFile ytFile = ytFiles.get(YOUTUBE_ITAG_140);
                if (ytFile == null) {
                    ytFile = ytFiles.get(YOUTUBE_ITAG_18);
                }
                try {
                    Log.d(TAG, "Start playback");
                    if (mMediaPlayer != null) {
                        mMediaPlayer.reset();
                        mMediaPlayer.setDataSource(ytFile.getUrl());
                        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mMediaPlayer.prepare();
                        mMediaPlayer.start();
                    }
                } catch (IOException io) {
                    io.printStackTrace();
                }
            }
        }
    };
    ytEx.execute(youtubeLink);
}

From source file:com.kiandastream.musicplayer.MusicService.java

void processPlayRequest(String url) {
    if (song_playlist != null && song_playlist.size() > Integer.parseInt(url)) {

        System.out.println("i am in processPlayRequest before condition   " + url);
        if (mState == State.Starting) {
            System.out.println("i am in processPlayRequest condition State.Starting");
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {

                //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(url)).getSong_id()+".mp3";
                System.out.println(
                        "url of song playing is " + song_playlist.get(Integer.parseInt(url)).getSongurl());
                mPlayer.setDataSource(song_playlist.get(Integer.parseInt(url)).getSongurl());
                setNotification("Loading");
                mState = State.Preparing;
                //Setting title in notification bar
                /* setUpAsForeground(mSongTitle + " (loading)");*/
                setNotification("Loading");
                if (!mWifiLock.isHeld())
                    mWifiLock.acquire();

                mPlayer.prepareAsync();//from  w  w w.j  a  v  a  2 s.  c o  m

            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else if (mState == State.Stopped) {
            System.out.println("i am in processPlayRequest condition State.Complete");
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(url)).getSong_id()+".mp3";
                System.out.println(
                        "url of song playing is " + song_playlist.get(Integer.parseInt(url)).getSongurl());

                mPlayer.setDataSource(song_playlist.get(Integer.parseInt(url)).getSongurl());
                setNotification("Loading");
                mState = State.Preparing;
                //Setting title in notification bar

                if (!mWifiLock.isHeld())
                    mWifiLock.acquire();
                mPlayer.prepareAsync();

            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else if (mState == State.Paused) {
            System.out.println("i am in processPlayRequest condition .State.Paused");
            if (mPlayer != null) {
                mPlayer.reset();
            } else
                createMediaPlayerIfNeeded();

            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(url)).getSong_id()+".mp3";
                System.out.println(
                        "url of song playing is " + song_playlist.get(Integer.parseInt(url)).getSongurl());
                mPlayer.setDataSource(song_playlist.get(Integer.parseInt(url)).getSongurl());
                setNotification("Loading");
                mState = State.Preparing;

                //Setting title in notification bar

                mPlayer.prepareAsync();
                if (!mWifiLock.isHeld())
                    mWifiLock.acquire();
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            configAndStartMediaPlayer();
        } else if (mState == State.Playing) {
            System.out.println("i am in processPlayRequest condition .State.Playing");
            if (listener != null)
                listener.stopUpdating(mPlayer);
            mPlayer.pause();
            mPlayer.reset();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(url)).getSong_id()+".mp3";
                System.out.println(
                        "url of song playing is " + song_playlist.get(Integer.parseInt(url)).getSongurl());
                mPlayer.setDataSource(song_playlist.get(Integer.parseInt(url)).getSongurl());
                setNotification("Loading");
                mState = State.Preparing;
                //Setting title in notification bar

                mPlayer.prepareAsync();
                if (!mWifiLock.isHeld())
                    mWifiLock.acquire();

            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            configAndStartMediaPlayer();
        }
    }
}