android.media.AudioManager#requestAudioFocus ( )源码实例Demo

下面列出了android.media.AudioManager#requestAudioFocus ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Popeens-DSub   文件: Util.java
@TargetApi(8)
public static void requestAudioFocus(final Context context, final AudioManager audioManager) {
   	if(Build.VERSION.SDK_INT >= 26) {
   		if(audioFocusRequest == null) {
			AudioAttributes playbackAttributes = new AudioAttributes.Builder()
					.setUsage(AudioAttributes.USAGE_MEDIA)
					.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
					.build();

			audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
					.setAudioAttributes(playbackAttributes)
					.setOnAudioFocusChangeListener(getAudioFocusChangeListener(context, audioManager))
					.setWillPauseWhenDucked(true)
					.build();
			audioManager.requestAudioFocus(audioFocusRequest);
		}
	} else if (Build.VERSION.SDK_INT >= 8 && focusListener == null) {
   		audioManager.requestAudioFocus(focusListener = getAudioFocusChangeListener(context, audioManager), AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
   	}
   }
 
源代码2 项目: android-chromium   文件: MediaPlayerListener.java
@CalledByNative
private static MediaPlayerListener create(int nativeMediaPlayerListener,
        Context context, MediaPlayerBridge mediaPlayerBridge) {
    final MediaPlayerListener listener =
            new MediaPlayerListener(nativeMediaPlayerListener, context);
    mediaPlayerBridge.setOnBufferingUpdateListener(listener);
    mediaPlayerBridge.setOnCompletionListener(listener);
    mediaPlayerBridge.setOnErrorListener(listener);
    mediaPlayerBridge.setOnPreparedListener(listener);
    mediaPlayerBridge.setOnSeekCompleteListener(listener);
    mediaPlayerBridge.setOnVideoSizeChangedListener(listener);

    AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    am.requestAudioFocus(
            listener,
            AudioManager.STREAM_MUSIC,

            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    return listener;
}
 
源代码3 项目: bcm-android   文件: SignalAudioManager.java
public void initializeAudioForCall() {
  AudioManager audioManager = AppUtil.INSTANCE.getAudioManager(context);

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    audioManager.requestAudioFocus(null, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE);
  } else {
    audioManager.requestAudioFocus(null, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
  }
}
 
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mMediaPlayerGlue = new VideoMediaPlayerGlue(getActivity(),
            new MediaPlayerAdapter(getActivity()));
    mMediaPlayerGlue.setHost(mHost);
    AudioManager audioManager = (AudioManager) getActivity()
            .getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.w(TAG, "video player cannot obtain audio focus!");
    }

    mMediaPlayerGlue.setMode(PlaybackControlsRow.RepeatAction.NONE);
    MediaMetaData intentMetaData = getActivity().getIntent().getParcelableExtra(
            VideoExampleActivity.TAG);
    if (intentMetaData != null) {
        mMediaPlayerGlue.setTitle(intentMetaData.getMediaTitle());
        mMediaPlayerGlue.setSubtitle(intentMetaData.getMediaArtistName());
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(
                Uri.parse(intentMetaData.getMediaSourcePath()));
    } else {
        mMediaPlayerGlue.setTitle("Diving with Sharks");
        mMediaPlayerGlue.setSubtitle("A Googler");
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(Uri.parse(URL));
    }
    PlaybackSeekDiskDataProvider.setDemoSeekProvider(mMediaPlayerGlue);
    playWhenReady(mMediaPlayerGlue);
    setBackgroundType(BG_LIGHT);
}
 
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ExoPlayerAdapter playerAdapter = new ExoPlayerAdapter(getActivity());
    playerAdapter.setAudioStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
    mMediaPlayerGlue = new VideoMediaPlayerGlue(getActivity(), playerAdapter);
    mMediaPlayerGlue.setHost(mHost);
    AudioManager audioManager = (AudioManager) getActivity()
            .getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.w(TAG, "video player cannot obtain audio focus!");
    }

    mMediaPlayerGlue.setMode(PlaybackControlsRow.RepeatAction.NONE);
    MediaMetaData intentMetaData = getActivity().getIntent().getParcelableExtra(
            VideoExampleActivity.TAG);
    if (intentMetaData != null) {
        mMediaPlayerGlue.setTitle(intentMetaData.getMediaTitle());
        mMediaPlayerGlue.setSubtitle(intentMetaData.getMediaArtistName());
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(
                Uri.parse(intentMetaData.getMediaSourcePath()));
    } else {
        mMediaPlayerGlue.setTitle("Diving with Sharks");
        mMediaPlayerGlue.setSubtitle("A Googler");
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(Uri.parse(URL));
    }
    PlaybackSeekDiskDataProvider.setDemoSeekProvider(mMediaPlayerGlue);
    playWhenReady(mMediaPlayerGlue);
    setBackgroundType(BG_LIGHT);
}
 
源代码6 项目: Pix-Art-Messenger   文件: MediaViewerActivity.java
private void requestAudioFocus() {
    AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    if (am != null) {
        am.requestAudioFocus(this,
                AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    }
}
 
源代码7 项目: CodenameOne   文件: Audio.java
public Audio(Activity activity, MediaPlayer player, InputStream stream, Runnable onComplete) {
    this.activity = activity;
    this.player = player;
    this.stream = stream;
    if (onComplete != null) {
        addCompletionHandler(onComplete);
    }
    
    bindPlayerCleanupOnComplete();

    AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
    int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
}
 
源代码8 项目: 365browser   文件: AudioFocusDelegate.java
private boolean requestAudioFocusInternal() {
    AudioManager am = (AudioManager) ContextUtils.getApplicationContext().getSystemService(
            Context.AUDIO_SERVICE);

    int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC, mFocusType);
    return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
 
源代码9 项目: Telegram   文件: WebPlayerView.java
private void checkAudioFocus() {
    if (!hasAudioFocus) {
        AudioManager audioManager = (AudioManager) ApplicationLoader.applicationContext.getSystemService(Context.AUDIO_SERVICE);
        hasAudioFocus = true;
        if (audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            audioFocus = 2;
        }
    }
}
 
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ExoPlayerAdapter playerAdapter = new ExoPlayerAdapter(getActivity());
    playerAdapter.setAudioStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
    mMediaPlayerGlue = new VideoMediaPlayerGlue(getActivity(), playerAdapter);
    mMediaPlayerGlue.setHost(mHost);
    AudioManager audioManager = (AudioManager) getActivity()
            .getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.w(TAG, "video player cannot obtain audio focus!");
    }

    mMediaPlayerGlue.setMode(PlaybackControlsRow.RepeatAction.NONE);
    MediaMetaData intentMetaData = getActivity().getIntent().getParcelableExtra(
            VideoExampleActivity.TAG);
    if (intentMetaData != null) {
        mMediaPlayerGlue.setTitle(intentMetaData.getMediaTitle());
        mMediaPlayerGlue.setSubtitle(intentMetaData.getMediaArtistName());
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(
                Uri.parse(intentMetaData.getMediaSourcePath()));
    } else {
        mMediaPlayerGlue.setTitle("Diving with Sharks");
        mMediaPlayerGlue.setSubtitle("A Googler");
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(Uri.parse(URL));
    }
    PlaybackSeekDiskDataProvider.setDemoSeekProvider(mMediaPlayerGlue);
    playWhenReady(mMediaPlayerGlue);
    setBackgroundType(BG_LIGHT);
}
 
源代码11 项目: CodenameOne   文件: BackgroundAudioService.java
private boolean successfullyRetrievedAudioFocus() {
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    int result = audioManager.requestAudioFocus(this,
            AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    return result == AudioManager.AUDIOFOCUS_GAIN;
}
 
源代码12 项目: QuickLyric   文件: MainActivity.java
@SuppressLint("InlinedApi")
public static void resync(Context context) {
    AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    am.requestAudioFocus(null,
            // Use the music stream.
            AudioManager.STREAM_SYSTEM,
            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    am.abandonAudioFocus(null);
}
 
源代码13 项目: TelePlus-Android   文件: VoIPBaseService.java
protected void configureDeviceForCall() {
	needPlayEndSound = true;
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if(!USE_CONNECTION_SERVICE){
		am.setMode(AudioManager.MODE_IN_COMMUNICATION);
		am.requestAudioFocus(this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);
		if(isBluetoothHeadsetConnected() && hasEarpiece()){
			switch(audioRouteToSet){
				case AUDIO_ROUTE_BLUETOOTH:
					if(!bluetoothScoActive){
						needSwitchToBluetoothAfterScoActivates=true;
						try {
							am.startBluetoothSco();
						} catch (Throwable ignore) {

						}
					}else{
						am.setBluetoothScoOn(true);
						am.setSpeakerphoneOn(false);
					}
					break;
				case AUDIO_ROUTE_EARPIECE:
					am.setBluetoothScoOn(false);
					am.setSpeakerphoneOn(false);
					break;
				case AUDIO_ROUTE_SPEAKER:
					am.setBluetoothScoOn(false);
					am.setSpeakerphoneOn(true);
					break;
			}
		}else if(isBluetoothHeadsetConnected()){
			am.setBluetoothScoOn(speakerphoneStateToSet);
		}else{
			am.setSpeakerphoneOn(speakerphoneStateToSet);
		}
	}/*else{
		if(isBluetoothHeadsetConnected() && hasEarpiece()){
			switch(audioRouteToSet){
				case AUDIO_ROUTE_BLUETOOTH:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);
					break;
				case AUDIO_ROUTE_EARPIECE:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_WIRED_OR_EARPIECE);
					break;
				case AUDIO_ROUTE_SPEAKER:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_SPEAKER);
					break;
			}
		}else{
			if(hasEarpiece())
				systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_SPEAKER);
			else
				systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_BLUETOOTH);
		}
	}*/
	updateOutputGainControlState();
	audioConfigured=true;

	SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
	Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
	try{
		if(proximity!=null){
			proximityWakelock=((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "telegram-voip-prx");
			sm.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL);
		}
	}catch(Exception x){
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("Error initializing proximity sensor", x);
		}
	}
}
 
源代码14 项目: Telegram   文件: VoIPBaseService.java
protected void configureDeviceForCall() {
	needPlayEndSound = true;
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if(!USE_CONNECTION_SERVICE){
		am.setMode(AudioManager.MODE_IN_COMMUNICATION);
		am.requestAudioFocus(this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);
		if(isBluetoothHeadsetConnected() && hasEarpiece()){
			switch(audioRouteToSet){
				case AUDIO_ROUTE_BLUETOOTH:
					if(!bluetoothScoActive){
						needSwitchToBluetoothAfterScoActivates=true;
						try {
							am.startBluetoothSco();
						} catch (Throwable ignore) {

						}
					}else{
						am.setBluetoothScoOn(true);
						am.setSpeakerphoneOn(false);
					}
					break;
				case AUDIO_ROUTE_EARPIECE:
					am.setBluetoothScoOn(false);
					am.setSpeakerphoneOn(false);
					break;
				case AUDIO_ROUTE_SPEAKER:
					am.setBluetoothScoOn(false);
					am.setSpeakerphoneOn(true);
					break;
			}
		}else if(isBluetoothHeadsetConnected()){
			am.setBluetoothScoOn(speakerphoneStateToSet);
		}else{
			am.setSpeakerphoneOn(speakerphoneStateToSet);
		}
	}/*else{
		if(isBluetoothHeadsetConnected() && hasEarpiece()){
			switch(audioRouteToSet){
				case AUDIO_ROUTE_BLUETOOTH:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);
					break;
				case AUDIO_ROUTE_EARPIECE:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_WIRED_OR_EARPIECE);
					break;
				case AUDIO_ROUTE_SPEAKER:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_SPEAKER);
					break;
			}
		}else{
			if(hasEarpiece())
				systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_SPEAKER);
			else
				systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_BLUETOOTH);
		}
	}*/
	updateOutputGainControlState();
	audioConfigured=true;

	SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
	Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
	try{
		if(proximity!=null){
			proximityWakelock=((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "telegram-voip-prx");
			sm.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL);
		}
	}catch(Exception x){
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("Error initializing proximity sensor", x);
		}
	}
}
 
源代码15 项目: LibreAlarm   文件: WearService.java
private void runTextToSpeech(PredictionData data) {

        if (!PreferencesUtil.getBoolean(this, getString(R.string.pref_key_text_to_speech))) return;

        boolean alarmOnly = PreferencesUtil.getBoolean(this, getString(R.string.pref_key_text_to_speech_only_alarm));

        if (alarmOnly && AlertRules.checkDontPostpone(this, data) == AlertRules.Danger.NOTHING) return;

        AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);
        manager.requestAudioFocus(mAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

        String message;

        if (data.errorCode == PredictionData.Result.OK) {
            boolean isMmol = PreferencesUtil.getBoolean(this, getString(R.string.pref_key_mmol), true);
            String glucose = data.glucose(isMmol);

            AlgorithmUtil.TrendArrow arrow = AlgorithmUtil.getTrendArrow(data);
            String trend;
            switch (arrow) {
                case UP:
                    trend = getString(R.string.text_to_speech_trend_up);
                    break;
                case DOWN:
                    trend = getString(R.string.text_to_speech_trend_down);
                    break;
                case SLIGHTLY_UP:
                    trend = getString(R.string.text_to_speech_trend_slightly_up);
                    break;
                case SLIGHTLY_DOWN:
                    trend = getString(R.string.text_to_speech_trend_slightly_down);
                    break;
                case FLAT:
                    trend = getString(R.string.text_to_speech_trend_flat);
                    break;
                case UNKNOWN:
                default:
                    trend = getString(R.string.text_to_speech_trend_unknown);
                    break;
            }
            message = getString(R.string.text_to_speech_message, glucose, trend);
        } else {
            message = getString(R.string.text_to_speech_error);
        }

        if (Build.VERSION.SDK_INT < 21) {
            HashMap<String, String> map = new HashMap<>();
            map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "glucose-speech");
            mTextToSpeech.speak(message, TextToSpeech.QUEUE_FLUSH, map);
        } else {
            mTextToSpeech.speak(message, TextToSpeech.QUEUE_FLUSH, null, "glucose-speech");
        }

    }
 
源代码16 项目: TelePlus-Android   文件: VoIPBaseService.java
protected void configureDeviceForCall() {
	needPlayEndSound = true;
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if(!USE_CONNECTION_SERVICE){
		am.setMode(AudioManager.MODE_IN_COMMUNICATION);
		am.requestAudioFocus(this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);
		if(isBluetoothHeadsetConnected() && hasEarpiece()){
			switch(audioRouteToSet){
				case AUDIO_ROUTE_BLUETOOTH:
					if(!bluetoothScoActive){
						needSwitchToBluetoothAfterScoActivates=true;
						try {
							am.startBluetoothSco();
						} catch (Throwable ignore) {

						}
					}else{
						am.setBluetoothScoOn(true);
						am.setSpeakerphoneOn(false);
					}
					break;
				case AUDIO_ROUTE_EARPIECE:
					am.setBluetoothScoOn(false);
					am.setSpeakerphoneOn(false);
					break;
				case AUDIO_ROUTE_SPEAKER:
					am.setBluetoothScoOn(false);
					am.setSpeakerphoneOn(true);
					break;
			}
		}else if(isBluetoothHeadsetConnected()){
			am.setBluetoothScoOn(speakerphoneStateToSet);
		}else{
			am.setSpeakerphoneOn(speakerphoneStateToSet);
		}
	}/*else{
		if(isBluetoothHeadsetConnected() && hasEarpiece()){
			switch(audioRouteToSet){
				case AUDIO_ROUTE_BLUETOOTH:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);
					break;
				case AUDIO_ROUTE_EARPIECE:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_WIRED_OR_EARPIECE);
					break;
				case AUDIO_ROUTE_SPEAKER:
					systemCallConnection.setAudioRoute(CallAudioState.ROUTE_SPEAKER);
					break;
			}
		}else{
			if(hasEarpiece())
				systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_SPEAKER);
			else
				systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_BLUETOOTH);
		}
	}*/
	updateOutputGainControlState();
	audioConfigured=true;

	SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
	Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
	try{
		if(proximity!=null){
			proximityWakelock=((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "telegram-voip-prx");
			sm.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL);
		}
	}catch(Exception x){
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("Error initializing proximity sensor", x);
		}
	}
}
 
源代码17 项目: DanDanPlayForAndroid   文件: IjkVideoView.java
@TargetApi(Build.VERSION_CODES.M)
private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;
    }
    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);
    // 声音控制
    AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
    am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    try {
        mMediaPlayer = createPlayer();

        // REMOVED: mAudioSession
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
        mMediaPlayer.setOnTimedTextListener(mTimedTextListener);
        mCurrentBufferPercentage = 0;
        String scheme = mUri.getScheme();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && mIsUsingMediaDataSource &&
                (TextUtils.isEmpty(scheme) || "file".equalsIgnoreCase(scheme))) {
            IMediaDataSource dataSource = new FileMediaDataSource(new File(mUri.toString()));
            mMediaPlayer.setDataSource(dataSource);
        } else {
            mMediaPlayer.setDataSource(mAppContext, mUri, mHeaders);
        }
        bindSurfaceHolder(mMediaPlayer, mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mPrepareStartTime = System.currentTimeMillis();
        mMediaPlayer.prepareAsync();

        // REMOVED: mPendingSubtitleTracks

        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = MediaPlayerParams.STATE_PREPARING;
        attachMediaController();
    } catch (IOException | IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        mCurrentState = MediaPlayerParams.STATE_ERROR;
        mTargetState = MediaPlayerParams.STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
    } finally {
        // REMOVED: mPendingSubtitleTracks.clear();
        _notifyMediaStatus();
    }
}
 
源代码18 项目: TigerVideo   文件: VideoPlayerView.java
/**
 * 请求获取AudioFocus
 */
private void requestAudioFocus() {

    AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
    audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
 
源代码19 项目: IdealMedia   文件: PlayerService.java
@Override
public void onCreate() {
	super.onCreate();

	// initialize default output device
	if (!BASS.BASS_Init(-1, 44100, 0)) {
		return;
	}

	// look for plugins
	plugins = "";
       String path = getApplicationInfo().nativeLibraryDir;
	String[] list = new File(path).list();
	for (String s: list) {
		int plug = BASS.BASS_PluginLoad(path+"/"+s, 0);
		if (plug != 0) { // plugin loaded...
			plugins += s + "\n"; // add it to the list
		}
	}
	if (plugins.equals(""))
           plugins = "no plugins - visit the BASS webpage to get some\n";
	if(playerInterface != null) {
		playerInterface.onPluginsLoaded(plugins);
	}

       BASS.BASS_SetConfig(BASS.BASS_CONFIG_BUFFER, 1000);
       Log.w("BASS.BASS_CONFIG_BUFFER", "" + BASS.BASS_GetConfig(BASS.BASS_CONFIG_BUFFER));

	// Pending Intend
	Intent intent = new Intent(this, NavigationActivity.class);
	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
	pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

       //tracklist
       loadTracks();
       loadEqualizerValues();

       tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
       tm.listen(telephone, PhoneStateListener.LISTEN_CALL_STATE);

       myBroadcastReceiver = new ServiceBroadcastReceiver();
       IntentFilter intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
       intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION");
       intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
       registerReceiver(myBroadcastReceiver, intentFilter);

       ComponentName rcvMedia = new ComponentName(getPackageName(), MediaControlReceiver.class.getName());
       mAudioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
       mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
       mAudioManager.registerMediaButtonEventReceiver(rcvMedia);

       // Use the remote control APIs (if available) to set the playback state
       if (Build.VERSION.SDK_INT >= 14 && remoteControlClient == null) {
           registerRemoteControl(rcvMedia);
       }
}
 
源代码20 项目: DMusic   文件: MediaManager.java
public IMediaPlayer prepare(Context context, final Uri uri, final Map<String, String> heads, boolean looping) {
    if (context == null || uri == null) {
        return null;
    }
    currentState = STATE_PREPARING;
    currentBufferPercentage = 0;
    seekWhenPrepared = 0;
    // We shouldn't clear the target state, because somebody might have
    // called start() previously
    release(context, false);
    AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    // AudioManager.AUDIOFOCUS_GAIN / AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
    am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    try {
        mediaPlayer = Factory.createPlayer(context, settings.getPlayer());
        if (mediaPlayer == null) {
            return null;
        }
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        String scheme = uri.getScheme();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && settings.getUsingMediaDataSource()
                && (TextUtils.isEmpty(scheme) || scheme.equalsIgnoreCase("file"))) {
            IMediaDataSource dataSource = new FileMediaDataSource(new File(uri.toString()));
            mediaPlayer.setDataSource(dataSource);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            mediaPlayer.setDataSource(context, uri, heads);
        } else {
            mediaPlayer.setDataSource(uri.toString());
        }
        mediaPlayer.setLooping(looping);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setScreenOnWhilePlaying(true);
        mediaPlayer.setOnSeekCompleteListener(this);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnInfoListener(this);
        mediaPlayer.setOnVideoSizeChangedListener(this);
        mediaPlayer.prepareAsync();
        return mediaPlayer;
    } catch (Exception e) {
        ULog.w("Unable to open content: " + uri + e);
        onError(mediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
        e.printStackTrace();
        return null;
    }
}