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.squalala.talkiewalkie.ui.activities.TalkActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_talk);
    ButterKnife.bind(this);

    connectedUserFragment = new ConnectedUserFragment();
    settingsFragment = new SettingsFragment();

    messageAdapter = new MessageAdapter(messages, new OnClickMessageListener() {
        @Override/*www. j  av  a2 s.  co  m*/
        public void onClickMessage(Message message) {
            message.setRead(false);
            recyclerView.getAdapter().notifyDataSetChanged();
            mMessages.add(message);
            playAudios();
        }
    });

    linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setStackFromEnd(true);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(messageAdapter);

    progressView.setVisibility(View.VISIBLE);
    btnUserOnline.setVisibility(View.GONE);
    txtWhatHappen.setVisibility(View.GONE);
    //    txtNumberUsers.setVisibility(View.GONE);
    txtWhoSpeak.setVisibility(View.GONE);

    session = ((App) getApplication()).getSession();
    mSocket = ((App) getApplication()).getSocket();
    mSocket.on(Socket.EVENT_CONNECT, onConnect);
    mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.on(KEY_NEW_MESSAGE, onNewMessage);
    mSocket.on(KEY_JOIN_ROOM, onJoinRoom);
    mSocket.on(KEY_LEFT_ROOM, onLeftRoom);
    mSocket.on(KEY_NUMBER_USERS, onNumberUsers);
    mSocket.on(KEY_CONNECTED_USERS, onConnectedUsers);

    mSocket.connect();
    /*
            if (session.isBeep())
    iconBeep.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_up_black_48dp));
            else
    iconBeep.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_off_black_48dp));  */

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

    //   int maxVolume = amanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

    //  System.out.println("Max volume " + maxVolume);
    //  System.out.println("session Max volume " + session.getSoundVolume());
    amanager.setStreamVolume(AudioManager.STREAM_MUSIC, session.getSoundVolume(amanager), 0);

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayerForBeep.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @DebugLog
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            viewAvatar.setVisibility(View.GONE);
            //  pulsator.stop();

            if (session.isAutomaticPlay())
                playAudios();
        }
    });

    mIvVoiceIndicators = new ArrayList<>();
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator1));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator2));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator3));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator4));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator5));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator6));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator7));

    mAudioRecorder = AudioRecorder.getInstance();
    mRxAudioPlayer = RxAudioPlayer.getInstance();
    mAudioRecorder.setOnErrorListener(this);

    btnSpeak.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                press2Record();
                break;
            case MotionEvent.ACTION_UP:
                release2Send();
                break;
            case MotionEvent.ACTION_CANCEL:
                release2Send();
                break;
            default:
                break;
            }

            return true;
        }
    });
}

From source file:android.widget.TiVideoView4.java

private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;//from  w w  w.  j a v a 2s  . co m
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    getContext().sendBroadcast(i);

    if (mMediaPlayer != null) {
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mIsPrepared = false;
        Log.v(TAG, "reset duration to -1 in openVideo");
        mDuration = -1;
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;
        if (URLUtil.isAssetUrl(mUri.toString())) { // DST: 20090606 detect asset url
            AssetFileDescriptor afd = null;
            try {
                String path = mUri.toString().substring("file:///android_asset/".length());
                afd = getContext().getAssets().openFd(path);
                mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            } finally {
                if (afd != null) {
                    afd.close();
                }
            }
        } else {
            setDataSource();
        }
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.prepareAsync();
        attachMediaController();
    } catch (IOException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        return;
    } catch (IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        return;
    }
}

From source file:com.youku.player.base.YoukuBasePlayerActivity.java

/**
 * ?YoukuPlayersetIEncryptVideoCallBack?
 * YoukuBasePlayerActivity??call???// www .j a va  2s.c o m
 */
//   public boolean isApiServiceAvailable = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    Logger.d("PlayFlow", "YoukuBasePlayerActivity->onCreate");
    if (DEVELOPER_MODE) {
        StrictMode.setThreadPolicy(
                new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // ??detectAll()
                        // ?I/O
                        .penaltyLog() // ?logcat??dropbox?log
                        .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() // SQLite???
                .penaltyLog() // ?logcat
                .penaltyDeath().build());
    }

    super.onCreate(savedInstanceState);
    /*      isApiServiceAvailable = PlayerUiUtile.isYoukuPlayerServiceAvailable(this);
            if(!isApiServiceAvailable){
             return;
          }
            
          PlayerUiUtile.initialYoukuPlayerService(this);
          mediaPlayerDelegate = RemoteInterface.mediaPlayerDelegate;*/

    if (mCreateTime == 0) {
        // ????
        Profile.getVideoQualityFromSharedPreferences(getApplicationContext());
    }
    ++mCreateTime;
    youkuContext = this;
    mImageWorker = (ImageResizer) getImageWorker(this);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    OfflineStatistics offline = new OfflineStatistics();
    offline.sendVV(this);

    ACTIVE_TIME = PreferenceUtil.getPreference(this, "active_time");
    if (ACTIVE_TIME == null || ACTIVE_TIME.length() == 0) {
        ACTIVE_TIME = String.valueOf(System.currentTimeMillis());
        PreferenceUtil.savePreference(this, "active_time", ACTIVE_TIME);
    }

    // ??
    Profile.GUID = Device.guid;
    try {
        YoukuBasePlayerActivity.versionName = getPackageManager().getPackageInfo(getPackageName(),
                PackageManager.GET_META_DATA).versionName;
    } catch (NameNotFoundException e) {
        YoukuBasePlayerActivity.versionName = "3.1";
        Logger.e(TAG_GLOBAL, e);
    }

    if (TextUtils.isEmpty(com.baseproject.utils.Profile.User_Agent)) {
        String plant = UIUtils.isTablet(this) ? "Youku HD;" : "Youku;";
        com.baseproject.utils.Profile.initProfile("player", plant + versionName + ";Android;"
                + android.os.Build.VERSION.RELEASE + ";" + android.os.Build.MODEL, getApplicationContext());
    }

    //      mApplication = PlayerApplication.getPlayerApplicationInstance();
    flags = getApplicationInfo().flags;
    com.baseproject.utils.Profile.mContext = getApplicationContext();
    if (MediaPlayerProxyUtil.isUplayerSupported()) { //-------------------->
        YoukuBasePlayerActivity.isHighEnd = true;
        // 
        PreferenceUtil.savePreference(this, "isSoftwareDecode", true);
        com.youku.player.goplay.Profile
                .setVideoType_and_PlayerType(com.youku.player.goplay.Profile.FORMAT_FLV_HD, this);
    } else {
        YoukuBasePlayerActivity.isHighEnd = false;
        com.youku.player.goplay.Profile
                .setVideoType_and_PlayerType(com.youku.player.goplay.Profile.FORMAT_3GPHD, this);
    }

    IMediaPlayerDelegate.is = getResources().openRawResource(R.raw.aes); //-------------------------------------->
    orientationHelper = new DeviceOrientationHelper(this, this);
}

From source file:com.murati.oszk.audiobook.playback.LocalPlayback.java

private void tryToGetAudioFocus() {
    LogHelper.d(TAG, "tryToGetAudioFocus");
    int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        mCurrentAudioFocusState = AUDIO_FOCUSED;
    } else {/*from   w  ww.  j  av  a 2s.c  om*/
        mCurrentAudioFocusState = AUDIO_NO_FOCUS_NO_DUCK;
    }
}

From source file:net.sf.asap.PlayerService.java

public void run() {
    // read file/*from   w  w  w  .  j ava 2s  . c o  m*/
    String filename = uri.getPath();
    byte[] module = new byte[ASAPInfo.MAX_MODULE_LENGTH];
    int moduleLen;
    try {
        InputStream is;
        switch (uri.getScheme()) {
        case "file":
            if (Util.isZip(filename)) {
                String zipFilename = filename;
                filename = uri.getFragment();
                is = new ZipInputStream(zipFilename, filename);
            } else
                is = new FileInputStream(filename);
            break;
        case "http":
            is = httpGet(uri);
            break;
        default:
            throw new FileNotFoundException(uri.toString());
        }
        moduleLen = Util.readAndClose(is, module);
    } catch (IOException ex) {
        showError(R.string.error_reading_file);
        return;
    }

    // load file
    try {
        asap.load(filename, module, moduleLen);
        info = asap.getInfo();
        switch (song) {
        case SONG_DEFAULT:
            song = info.getDefaultSong();
            break;
        case SONG_LAST:
            song = info.getSongs() - 1;
            break;
        default:
            break;
        }
        playSong();
    } catch (Exception ex) {
        showError(R.string.invalid_file);
        return;
    }

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Player.class), 0);
    String title = info.getTitleOrFilename();
    Notification notification = new Notification(R.drawable.icon, title, System.currentTimeMillis());
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notification.setLatestEventInfo(this, title, info.getAuthor(), contentIntent);
    startForegroundCompat(NOTIFICATION_ID, notification);

    // playback
    int channelConfig = info.getChannels() == 1 ? AudioFormat.CHANNEL_CONFIGURATION_MONO
            : AudioFormat.CHANNEL_CONFIGURATION_STEREO;
    int bufferLen = AudioTrack.getMinBufferSize(ASAP.SAMPLE_RATE, channelConfig,
            AudioFormat.ENCODING_PCM_16BIT) >> 1;
    if (bufferLen < 16384)
        bufferLen = 16384;
    final byte[] byteBuffer = new byte[bufferLen << 1];
    final short[] shortBuffer = new short[bufferLen];
    audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, ASAP.SAMPLE_RATE, channelConfig,
            AudioFormat.ENCODING_PCM_16BIT, bufferLen << 1, AudioTrack.MODE_STREAM);
    audioTrack.play();

    for (;;) {
        synchronized (this) {
            if (bufferLen < shortBuffer.length || isPaused()) {
                try {
                    wait();
                } catch (InterruptedException ex) {
                }
            }
            if (stop) {
                audioTrack.stop();
                return;
            }
        }
        synchronized (asap) {
            int pos = seekPosition;
            if (pos >= 0) {
                seekPosition = -1;
                try {
                    asap.seek(pos);
                } catch (Exception ex) {
                }
            }
            bufferLen = asap.generate(byteBuffer, byteBuffer.length, ASAPSampleFormat.S16_L_E) >> 1;
        }
        for (int i = 0; i < bufferLen; i++)
            shortBuffer[i] = (short) ((byteBuffer[i << 1] & 0xff) | byteBuffer[i << 1 | 1] << 8);
        audioTrack.write(shortBuffer, 0, bufferLen);
    }
}

From source file:net.simno.klingar.playback.LocalPlayback.java

private void tryToGetAudioFocus() {
    Timber.d("tryToGetAudioFocus");
    int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        audioFocus = AUDIO_FOCUSED;//ww  w. j  a va2 s .  c  o m
    } else {
        audioFocus = AUDIO_NO_FOCUS_NO_DUCK;
    }
}

From source file:com.lybeat.lilyplayer.widget.media.IjkVideoView.java

private void initGestureScanner(final Context context) {
    slop = ViewConfiguration.get(context).getScaledTouchSlop();
    screenWidth = ScreenUtil.getScreenWidth(context);
    gestureDetector = new GestureDetectorCompat(context, new LilyGestureListener());
    setOnTouchListener(new OnTouchListener() {
        @Override//  w  w  w .j  av a 2  s  . c  om
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_UP:
                if (adjustProgress) {
                    adjustProgress = false;
                    int newPosition = (int) (getCurrentPosition() + scrollX / screenWidth * 1000 * 90);
                    if (newPosition < 0) {
                        seekTo(0);
                    } else {
                        seekTo(newPosition);
                    }
                    start();
                    mAdjustProgressView.setVisibility(GONE);
                    if (mMediaController.isShowing()) {
                        showAllBoard();
                    }
                }
                scrollX = 0;
                scrollY = 0;
                level = 0;
                adjustVolume = false;
                adjustBrightness = false;
                break;
            case MotionEvent.ACTION_DOWN:
                lastX = motionEvent.getRawX();
                lastY = motionEvent.getRawY();
                if (motionEvent.getRawX() > screenWidth / 2 + 150) {
                    adjustVolume = true;
                    adjustBrightness = false;
                } else if (motionEvent.getRawX() < screenWidth / 2 - 150) {
                    adjustBrightness = true;
                    adjustVolume = false;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (adjustProgress) {
                    break;
                }
                if (Math.abs(motionEvent.getRawY() - lastY) > Math.abs(motionEvent.getRawX() - lastX)) {

                    AudioManager audioManager = (AudioManager) mAppContext
                            .getSystemService(Context.AUDIO_SERVICE);
                    if (motionEvent.getRawY() > lastY) {
                        level += motionEvent.getRawY() - lastY;
                        if (level > slop) {
                            if (adjustVolume) {
                                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                        AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
                            } else if (adjustBrightness) {
                                float brightness = ScreenUtil.getScreenBrightness((Activity) context);
                                if (brightness <= 0.1f) {
                                    ScreenUtil.setScreenBrightness((Activity) context, 0.0f);
                                } else {
                                    ScreenUtil.setScreenBrightness((Activity) context,
                                            ScreenUtil.getScreenBrightness((Activity) context) - 0.1f);
                                }
                            }
                            level = 0;
                        }
                    } else {
                        level += lastY - motionEvent.getRawY();
                        if (level > slop) {
                            if (adjustVolume) {
                                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                        AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
                            } else if (adjustBrightness) {
                                float brightness = ScreenUtil.getScreenBrightness((Activity) context);
                                if (brightness >= 0.9f) {
                                    ScreenUtil.setScreenBrightness((Activity) context, 1.0f);
                                } else {
                                    ScreenUtil.setScreenBrightness((Activity) context,
                                            ScreenUtil.getScreenBrightness((Activity) context) + 0.1f);
                                }
                            }
                            level = 0;
                        }
                    }
                }
                lastX = motionEvent.getRawX();
                lastY = motionEvent.getRawY();
                break;
            }

            return gestureDetector.onTouchEvent(motionEvent);
        }
    });
}

From source file:com.dmplayer.manager.MusicPlayerService.java

@SuppressLint("NewApi")
private void createNotification(SongDetail mSongDetail) {
    try {//w ww.ja va2 s.  c  o  m
        String songName = mSongDetail.getTitle();
        String authorName = mSongDetail.getArtist();
        SongDetail audioInfo = MediaController.getInstance().getPlayingSongDetail();

        RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(),
                R.layout.player_small_notification);
        RemoteViews expandedView = null;
        if (supportBigNotifications) {
            expandedView = new RemoteViews(getApplicationContext().getPackageName(),
                    R.layout.player_big_notification);
        }

        Intent intent = new Intent(ApplicationDMPlayer.applicationContext, DMPlayerBaseActivity.class);
        intent.setAction("openplayer");
        intent.setFlags(32768);
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationDMPlayer.applicationContext, 0,
                intent, 0);

        Notification notification = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.player).setContentIntent(contentIntent).setContentTitle(songName)
                .build();

        notification.contentView = simpleContentView;
        if (supportBigNotifications) {
            notification.bigContentView = expandedView;
        }

        setListeners(simpleContentView);
        if (supportBigNotifications) {
            setListeners(expandedView);
        }

        Bitmap albumArt = audioInfo != null ? audioInfo.getSmallCover(ApplicationDMPlayer.applicationContext)
                : null;

        if (albumArt != null) {
            notification.contentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            if (supportBigNotifications) {
                notification.bigContentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            }
        } else {
            notification.contentView.setImageViewResource(R.id.player_album_art,
                    R.drawable.bg_default_album_art);
            if (supportBigNotifications) {
                notification.bigContentView.setImageViewResource(R.id.player_album_art,
                        R.drawable.bg_default_album_art);
            }
        }
        notification.contentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_next, View.VISIBLE);
        notification.contentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
        if (supportBigNotifications) {
            notification.bigContentView.setViewVisibility(R.id.player_next, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        }

        if (MediaController.getInstance().isAudioPaused()) {
            notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
            notification.contentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            }
        } else {
            notification.contentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
            notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
            }
        }

        notification.contentView.setTextViewText(R.id.player_song_name, songName);
        notification.contentView.setTextViewText(R.id.player_author_name, authorName);
        if (supportBigNotifications) {
            notification.bigContentView.setTextViewText(R.id.player_song_name, songName);
            notification.bigContentView.setTextViewText(R.id.player_author_name, authorName);
        }
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        startForeground(5, notification);

        if (remoteControlClient != null) {
            RemoteControlClient.MetadataEditor metadataEditor = remoteControlClient.editMetadata(true);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, authorName);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, songName);
            if (audioInfo != null && audioInfo.getCover(ApplicationDMPlayer.applicationContext) != null) {
                metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK,
                        audioInfo.getCover(ApplicationDMPlayer.applicationContext));
            }
            metadataEditor.apply();
            audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.mantraideas.androidaudio.manager.MusicPlayerService.java

@SuppressLint("NewApi")
private void createNotification(SongDetail mSongDetail) {
    try {//from  w  w  w. j  a v  a 2  s .  com
        String songName = mSongDetail.getTitle();
        String authorName = mSongDetail.getArtist();
        SongDetail audioInfo = MediaController.getInstance().getPlayingSongDetail();

        RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(),
                R.layout.player_small_notification);
        RemoteViews expandedView = null;
        if (supportBigNotifications) {
            expandedView = new RemoteViews(getApplicationContext().getPackageName(),
                    R.layout.player_big_notification);
        }

        Intent intent = new Intent(MyApplication.applicationContext, MainActivity.class);
        intent.setAction("openplayer");
        intent.setFlags(32768);
        PendingIntent contentIntent = PendingIntent.getActivity(MyApplication.applicationContext, 0, intent, 0);

        Notification notification = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.player).setContentIntent(contentIntent).setContentTitle(songName)
                .build();

        notification.contentView = simpleContentView;
        if (supportBigNotifications) {
            notification.bigContentView = expandedView;
        }

        setListeners(simpleContentView);
        if (supportBigNotifications) {
            setListeners(expandedView);
        }

        Bitmap albumArt = audioInfo != null ? audioInfo.getSmallCover(MyApplication.applicationContext) : null;

        if (albumArt != null) {
            notification.contentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            if (supportBigNotifications) {
                notification.bigContentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            }
        } else {
            notification.contentView.setImageViewResource(R.id.player_album_art,
                    R.drawable.bg_default_album_art);
            if (supportBigNotifications) {
                notification.bigContentView.setImageViewResource(R.id.player_album_art,
                        R.drawable.bg_default_album_art);
            }
        }
        notification.contentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_next, View.VISIBLE);
        notification.contentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
        if (supportBigNotifications) {
            notification.bigContentView.setViewVisibility(R.id.player_next, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        }

        if (MediaController.getInstance().isAudioPaused()) {
            notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
            notification.contentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            }
        } else {
            notification.contentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
            notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
            }
        }

        notification.contentView.setTextViewText(R.id.player_song_name, songName);
        notification.contentView.setTextViewText(R.id.player_author_name, authorName);
        if (supportBigNotifications) {
            notification.bigContentView.setTextViewText(R.id.player_song_name, songName);
            notification.bigContentView.setTextViewText(R.id.player_author_name, authorName);
        }
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        startForeground(5, notification);

        if (remoteControlClient != null) {
            RemoteControlClient.MetadataEditor metadataEditor = remoteControlClient.editMetadata(true);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, authorName);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, songName);
            if (audioInfo != null && audioInfo.getCover(MyApplication.applicationContext) != null) {
                metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK,
                        audioInfo.getCover(MyApplication.applicationContext));
            }
            metadataEditor.apply();
            audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

private void setupAudioPlayer() {
    audioPlayer = new CustomMediaPlayer();
    audioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    audioPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {

        @Override/*  w w w .j a  v a  2 s . co  m*/
        public void onBufferingUpdate(MediaPlayer player, int newCache) {
            Stream stream = playQueue.peek();
            if (stream == null) {
                return;
            }
            if (playbackStartedSuccessfully && !bufferUnderrunInProgress) {
                // We started buffering mid playback
                bufferUnderrunInProgress = true;
                long startOffset = 0;
                startOffset = stream.getOffsetInMilliseconds();
                playbackStutterStartedOffsetInMilliseconds = Math.max(startOffset,
                        getCurrentOffsetInMilliseconds());
                stopTimerAndProgressReporter();
                audioPlayerStateMachine.playbackStutterStarted();
            }

            if (bufferUnderrunInProgress && newCache >= 100.0f) {
                // We are fully buffered after a buffer underrun event
                bufferUnderrunInProgress = false;
                audioPlayerStateMachine.playbackStutterFinished();
                startTimerAndProgressReporter();
            }

            if (!playbackStartedSuccessfully && newCache >= 100.0f) {
                // We have successfully buffered the first time and started playback
                playbackStartedSuccessfully = true;

                long offset = stream.getOffsetInMilliseconds();

                timer.reset(offset, audioPlayer.getDuration());
                progressReporter.disable();
                if (stream.getProgressReportRequired()) {
                    progressReporter.setup(stream.getProgressReport());
                }

                audioPlayerStateMachine.playbackStarted();
                startTimerAndProgressReporter();

                if (isPaused) {
                    audioPlayerStateMachine.playbackPaused();
                }
            }
        }
    });

    audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer player) {
            CustomMediaPlayer mediaPlayer = (CustomMediaPlayer) player;
            Log.d("Audio finished", "Finished playing " + mediaPlayer.mrl());
            List<String> items = new ArrayList<String>();/*mediaPlayer.subItems();*/
            // Remember the url we just tried
            attemptedUrls.add(mediaPlayer.mrl());

            if (cachedAudioFiles.containsKey(mediaPlayer.mrl())) {
                String key = mediaPlayer.mrl();
                String cachedUrl = cachedAudioFiles.get(key);
                deleteCachedFile(cachedUrl);
                cachedAudioFiles.remove(key);
            }

            if ((items.size() > 0) || (streamUrls.size() > 0)) {
                // Add to the set of URLs to attempt playback
                streamUrls.addAll(items);

                // Play any url associated with this play item that
                // we haven't already tried
                for (String mrl : streamUrls) {
                    if (!attemptedUrls.contains(mrl)) {
                        Log.d("Playing {}", mrl);
                        try {
                            playAudio(mrl);
                            return;
                        } catch (IOException e) {
                            Log.d("Playing Error", e.getMessage(), e);
                        }
                    }
                }
            }

            // wait for any pending events to finish(playbackStarted/progressReport)
            while (controller.eventRunning()) {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
            }

            // remove the item from the queue since it has finished playing
            playQueue.poll();

            stopTimerAndProgressReporter();
            audioPlayerStateMachine.playbackNearlyFinished();
            audioPlayerStateMachine.playbackFinished();

            // unblock playback now that playbackFinished has been sent
            waitForPlaybackFinished = false;
            if (!playQueue.isEmpty()) {
                // start playback if it wasn't the last item
                startPlayback();
            }
        }
    });

    audioPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer player, int i, int i1) {
            CustomMediaPlayer mediaPlayer = (CustomMediaPlayer) player;
            Log.d("Error playing:", mediaPlayer.mrl());

            attemptedUrls.add(mediaPlayer.mrl());
            // If there are any urls left to try, don't throw an error
            for (String mrl : streamUrls) {
                if (!attemptedUrls.contains(mrl)) {
                    try {
                        playAudio(mrl);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return false;
                }
            }

            // wait for any pending events to finish(playbackStarted/progressReport)
            while (controller.eventRunning()) {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
            }
            playQueue.clear();
            stopTimerAndProgressReporter();
            audioPlayerStateMachine.playbackFailed();
            return false;
        }
    });
}