Example usage for android.media MediaPlayer setAudioSessionId

List of usage examples for android.media MediaPlayer setAudioSessionId

Introduction

In this page you can find the example usage for android.media MediaPlayer setAudioSessionId.

Prototype

public native void setAudioSessionId(int sessionId) throws IllegalArgumentException, IllegalStateException;

Source Link

Document

Sets the audio session ID.

Usage

From source file:github.daneren2005.dsub.service.DownloadService.java

@Override
public void onCreate() {
    super.onCreate();

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*from  www  . j a va2 s.com*/

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            audioSessionId = -1;
            Integer id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            if (id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();
                    prefs.edit().putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId).commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientHelper.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();
}

From source file:github.daneren2005.dsub.service.DownloadService.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {//from  w  w  w. ja  va  2 s.  co  m
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        boolean isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        String dataSource = file.getAbsolutePath();
        if (isPartial && !Util.isOffline(this)) {
            if (proxy == null) {
                proxy = new BufferProxy(this);
                proxy.start();
            }
            proxy.setBufferFile(downloadFile);
            dataSource = proxy.getPrivateAddress(dataSource);
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

From source file:github.popeen.dsub.service.DownloadService.java

@Override
public void onCreate() {
    super.onCreate();

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();//from   ww w  .  ja  va2s.  c om

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            // We want to change audio session id's between upgrading Android versions.  Upgrading to Android 7.0 is broken (probably updated session id format)
            audioSessionId = -1;
            int id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            int versionCode = prefs.getInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, -1);
            if (versionCode == Build.VERSION.SDK_INT && id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    Log.w(TAG, "Failed to use cached audio session", e);
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();

                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId);
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, Build.VERSION.SDK_INT);
                    editor.commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            /*try {
               Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
               i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
               i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
               sendBroadcast(i);
            } catch(Throwable e) {
               // Froyo or lower
            }*/

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);
    audioNoisyReceiver = new AudioNoisyReceiver();
    registerReceiver(audioNoisyReceiver, audioNoisyIntent);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientBase.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "downloadServiceLock");

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();

    if (Build.VERSION.SDK_INT >= 26) {
        Notifications.shutGoogleUpNotification(this);
    }
}

From source file:github.popeen.dsub.service.DownloadService.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {//w  ww.  java  2s.c  om
        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }

        String dataSource;
        boolean isPartial = false;
        if (downloadFile.isStream()) {
            dataSource = downloadFile.getStream();
            Log.i(TAG, "Data Source: " + dataSource);
        } else {
            downloadFile.setPlaying(true);
            final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                    : downloadFile.getPartialFile();
            isPartial = file.equals(downloadFile.getPartialFile());
            downloadFile.updateModificationDate();

            dataSource = file.getAbsolutePath();
            if (isPartial && !Util.isOffline(this)) {
                if (proxy == null) {
                    proxy = new BufferProxy(this);
                    proxy.start();
                }
                proxy.setBufferFile(downloadFile);
                dataSource = proxy.getPrivateAddress(dataSource);
                Log.i(TAG, "Data Source: " + dataSource);
            } else if (proxy != null) {
                proxy.stop();
                proxy = null;
            }
        }

        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            applyPlaybackParamsMain();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }

                        updateRemotePlaylist();
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}