Java Code Examples for android.media.MediaPlayer#setAudioStreamType()

The following examples show how to use android.media.MediaPlayer#setAudioStreamType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomVideoView.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
public void startPlay() {
        if (mSurfaceHolder == null) {
            return;
        }
        stopPlaying();
        // 关闭系统音乐声音
        try {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnPreparedListener(this);
            mIsPrepared = false;
            mMediaPlayer.setDisplay(mSurfaceHolder);
//            mMediaPlayer.setDataSource(mContext, Uri.parse("http://videojj-cdn.oss-cn-beijing.aliyuncs.com/flash/player/video/6.mp4"));
            mMediaPlayer.setDataSource(mContext, Uri.parse(mCurrentUrl));
//            mMediaPlayer.setDataSource(mContext, Uri.parse("https://static.videojj.com/online/video/Team%20Video%2B%2B_We_Are_Young.mp4"));
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.prepareAsync();
        } catch (Exception ex) {
            VenvyLog.e("media player error" + ex);
        }
    }
 
Example 2
Source File: KcaUtils.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
public static void playNotificationSound(MediaPlayer mediaPlayer, Context context, Uri uri) {
    try {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
        if (uri != null && !Uri.EMPTY.equals(uri)) {
            mediaPlayer.setDataSource(context, uri);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                AudioAttributes attr = new AudioAttributes.Builder()
                        .setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
                        .build();
                mediaPlayer.setAudioAttributes(attr);
            } else {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            }
            mediaPlayer.prepare();
            mediaPlayer.start();
        }
    } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: AlarmAlertActivity.java    From SpecialAlarmClock with Apache License 2.0 6 votes vote down vote up
private void startAlarm() {
    if (alarm.getAlarmTonePath() != "") {
        mediaPlayer = new MediaPlayer();
        if (alarm.IsVibrate()) {
            vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            long[] pattern = {1000, 200, 200, 200};
            vibrator.vibrate(pattern, 0);
        }
        try {
            mediaPlayer.setVolume(1.0f, 1.0f);
            mediaPlayer.setDataSource(this, Uri.parse(alarm.getAlarmTonePath()));
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mediaPlayer.setLooping(true);
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (Exception e) {
            mediaPlayer.release();
            alarmActive = false;
        }
    }

}
 
Example 4
Source File: BeepManager.java    From qrcode_android with GNU Lesser General Public License v3.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        Log.w(TAG, ioe);
        mediaPlayer.release();
        return null;
    }
}
 
Example 5
Source File: BeepManager.java    From QRScanner with GNU Lesser General Public License v3.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        Log.w(TAG, ioe);
        mediaPlayer.release();
        return null;
    }
}
 
Example 6
Source File: IncomingRinger.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private MediaPlayer createPlayer(@NonNull Uri ringtoneUri) {
  try {
    MediaPlayer mediaPlayer = new MediaPlayer();

    mediaPlayer.setOnErrorListener(new MediaPlayerErrorListener());
    mediaPlayer.setDataSource(context, ringtoneUri);
    mediaPlayer.setLooping(true);

    if (Build.VERSION.SDK_INT <= 21) {
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
    } else {
      mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                                                        .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                                                        .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING)
                                                        .build());
    }

    return mediaPlayer;
  } catch (IOException e) {
    Log.e(TAG, "Failed to create player for incoming call ringer");
    return null;
  }
}
 
Example 7
Source File: AudioPlayer.java    From GSYRecordWave with Apache License 2.0 6 votes vote down vote up
/**
 * 音频播放器
 *
 * @param context 上下文
 * @param handler 音频状态handler
 */
public AudioPlayer(Context context, Handler handler) {
    super();
    this.mRemoteHandler = handler;
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: MainActivity.java    From pretixdroid with GNU General Public License v3.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    // mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources()
                .openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(),
                    file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(0.10f, 0.10f);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        mediaPlayer.release();
        return null;
    }
}
 
Example 9
Source File: MediaPlayerImpl.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
public MediaPlayerImpl(Context context, PlayerAttributes attributes) {
    super(context, attributes);
    synchronized (LOCK) {
        mPlayer = new MediaPlayer();
    }
    mContext = context.getApplicationContext();
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    mPlayer.setOnCompletionListener(this);
    mPlayer.setOnErrorListener(this);
    mPlayer.setOnInfoListener(this);
    mPlayer.setOnPreparedListener(this);
    mPlayer.setOnSeekCompleteListener(this);
    mPlayer.setOnVideoSizeChangedListener(this);
    mPlayer.setOnBufferingUpdateListener(this);
}
 
Example 10
Source File: JZMediaSystem.java    From JZVideoDemo with MIT License 5 votes vote down vote up
@Override
public void prepare() {
    try {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        if (dataSourceObjects.length > 1) {
            mediaPlayer.setLooping((boolean) dataSourceObjects[1]);
        }
        mediaPlayer.setOnPreparedListener(JZMediaSystem.this);
        mediaPlayer.setOnCompletionListener(JZMediaSystem.this);
        mediaPlayer.setOnBufferingUpdateListener(JZMediaSystem.this);
        mediaPlayer.setScreenOnWhilePlaying(true);
        mediaPlayer.setOnSeekCompleteListener(JZMediaSystem.this);
        mediaPlayer.setOnErrorListener(JZMediaSystem.this);
        mediaPlayer.setOnInfoListener(JZMediaSystem.this);
        mediaPlayer.setOnVideoSizeChangedListener(JZMediaSystem.this);
        mediaPlayer.setVolume(0f, 0f);
        Class<MediaPlayer> clazz = MediaPlayer.class;
        Method method = clazz.getDeclaredMethod("setDataSource", String.class, Map.class);
        if (dataSourceObjects.length > 2) {
            method.invoke(mediaPlayer, currentDataSource.toString(), dataSourceObjects[2]);
        } else {
            method.invoke(mediaPlayer, currentDataSource.toString(), null);
        }
        mediaPlayer.prepareAsync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 11
Source File: AndroidMediaPlayer.java    From LivePlayback with Apache License 2.0 5 votes vote down vote up
public AndroidMediaPlayer() {
    synchronized (mInitLock) {
        mInternalMediaPlayer = new MediaPlayer();
    }
    mInternalMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mInternalListenerAdapter = new AndroidMediaPlayerListenerHolder(this);
    attachInternalListeners();
}
 
Example 12
Source File: Mp3PlayerService.java    From ampdroid with MIT License 5 votes vote down vote up
@Override
public void onCreate() {
	mediaPlayer = new MediaPlayer();
	mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	mediaPlayer.setOnCompletionListener(new SongComplitionListener());
	pause = false;
	session = "";

}
 
Example 13
Source File: MusicService.java    From Rey-MusicPlayer with Apache License 2.0 5 votes vote down vote up
private void initMediaPlayers() {
    mMediaPlayer1 = new MediaPlayer();
    mMediaPlayer1.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
    mMediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);


    if (mSongs.size() > 0) {
        startSong();
    }
}
 
Example 14
Source File: MultiPlayer.java    From Music-Player with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param player The {@link MediaPlayer} to use
 * @param path   The path of the file, or the http/rtsp URL of the stream
 *               you want to play
 * @return True if the <code>player</code> has been prepared and is
 * ready to play, false otherwise
 */
private boolean setDataSourceImpl(@NonNull final MediaPlayer player, @NonNull final String path) {
    if (context == null) {
        return false;
    }
    try {
        player.reset();
        player.setOnPreparedListener(null);
        if (path.startsWith("content://")) {
            player.setDataSource(context, Uri.parse(path));
        } else {
            player.setDataSource(path);
        }
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.prepare();
    } catch (Exception e) {
        return false;
    }
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
    intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
    intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName());
    intent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC);
    context.sendBroadcast(intent);
    return true;
}
 
Example 15
Source File: AndroidMusic.java    From Alite with GNU General Public License v3.0 5 votes vote down vote up
public AndroidMusic(AssetFileDescriptor afd, Sound.SoundType soundType, String fileName) throws IOException {
	mediaPlayer = new MediaPlayer();
	musicInfo = fileName;
	try {
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
		mediaPlayer.prepareAsync();
		mediaPlayer.setOnPreparedListener(this);
		mediaPlayer.setOnCompletionListener(this);
		this.soundType = soundType;
	} catch (Exception e) {
		AliteLog.e("Loading Music " + musicInfo + " caused an Error", e.getMessage(), e);
		throw new RuntimeException("Couldn't load music " + musicInfo + ".", e);
	} 
}
 
Example 16
Source File: EaseChatRowVoicePlayClickListener.java    From nono-android with GNU General Public License v3.0 4 votes vote down vote up
public void playVoice(String filePath) {
	if (!(new File(filePath).exists())) {
		return;
	}
	playMsgId = message.getMsgId();
	AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);

	mediaPlayer = new MediaPlayer();
	if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
		audioManager.setMode(AudioManager.MODE_NORMAL);
		audioManager.setSpeakerphoneOn(true);
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
	} else {
		audioManager.setSpeakerphoneOn(false);// 关闭扬声器
		// 把声音设定成Earpiece(听筒)出来,设定为正在通话中
		audioManager.setMode(AudioManager.MODE_IN_CALL);
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
	}
	try {
		mediaPlayer.setDataSource(filePath);
		mediaPlayer.prepare();
		mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				mediaPlayer.release();
				mediaPlayer = null;
				stopPlayVoice(); // stop animation
			}

		});
		isPlaying = true;
		currentPlayListener = this;
		mediaPlayer.start();
		showAnimation();

		// 如果是接收的消息
		if (message.direct() == EMMessage.Direct.RECEIVE) {
		    if (!message.isAcked() && chatType == ChatType.Chat) {
                    // 告知对方已读这条消息
		            EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
		    }
			if (!message.isListened() && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
				// 隐藏自己未播放这条语音消息的标志
				iv_read_status.setVisibility(View.INVISIBLE);
				message.setListened(true);
				EMClient.getInstance().chatManager().setMessageListened(message);
			}

		}

	} catch (Exception e) {
	    System.out.println();
	}
}
 
Example 17
Source File: MediaPlayerManager.java    From DMusic with Apache License 2.0 4 votes vote down vote up
private MediaPlayerManager() {
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setScreenOnWhilePlaying(true);
}
 
Example 18
Source File: UniversalVideoView.java    From LLApp with Apache License 2.0 4 votes vote down vote up
private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;
    }
    AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);
    try {
        mMediaPlayer = new MediaPlayer();

        if (mAudioSession != 0) {
            mMediaPlayer.setAudioSessionId(mAudioSession);
        } else {
            mAudioSession = mMediaPlayer.getAudioSessionId();
        }
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;
        mMediaPlayer.setDataSource(mContext, mUri);
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.prepareAsync();


        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = STATE_PREPARING;
        attachMediaController();
    } catch (IOException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
    }
}
 
Example 19
Source File: VoIPBaseService.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
protected void startRingtoneAndVibration(int chatID){
	SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount);
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	boolean needRing=am.getRingerMode()!=AudioManager.RINGER_MODE_SILENT;
	/*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
		try{
			int mode=Settings.Global.getInt(getContentResolver(), "zen_mode");
			if(needRing)
				needRing=mode==0;
		}catch(Exception ignore){}
	}*/
	if(needRing){
		if(!USE_CONNECTION_SERVICE){
			am.requestAudioFocus(this, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN);
		}
		ringtonePlayer=new MediaPlayer();
		ringtonePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
			@Override
			public void onPrepared(MediaPlayer mediaPlayer){
				ringtonePlayer.start();
			}
		});
		ringtonePlayer.setLooping(true);
		ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
		try{
			String notificationUri;
			if(prefs.getBoolean("custom_"+chatID, false))
				notificationUri=prefs.getString("ringtone_path_"+chatID, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
			else
				notificationUri=prefs.getString("CallsRingtonePath", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
			ringtonePlayer.setDataSource(this, Uri.parse(notificationUri));
			ringtonePlayer.prepareAsync();
		}catch(Exception e){
			FileLog.e(e);
			if(ringtonePlayer!=null){
				ringtonePlayer.release();
				ringtonePlayer=null;
			}
		}
		int vibrate;
		if(prefs.getBoolean("custom_"+chatID, false))
			vibrate=prefs.getInt("calls_vibrate_"+chatID, 0);
		else
			vibrate=prefs.getInt("vibrate_calls", 0);
		if((vibrate!=2 && vibrate!=4 && (am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE || am.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)) ||
				(vibrate==4 && am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE)){
			vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
			long duration=700;
			if(vibrate==1)
				duration/=2;
			else if(vibrate==3)
				duration*=2;
			vibrator.vibrate(new long[]{0, duration, 500}, 0);
		}
	}
}
 
Example 20
Source File: ActivityCallViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
public void playRingtone() {
    boolean canPlay = false;
    AudioManager am = (AudioManager) G.context.getSystemService(Context.AUDIO_SERVICE);

    switch (am.getRingerMode()) {
        case AudioManager.RINGER_MODE_SILENT:
            canPlay = false;
            break;
        case AudioManager.RINGER_MODE_VIBRATE:
            canPlay = false;

            vibrator = (Vibrator) G.context.getSystemService(Context.VIBRATOR_SERVICE);
            long[] pattern = {0, 100, 1000};
            vibrator.vibrate(pattern, 0);

            break;
        case AudioManager.RINGER_MODE_NORMAL:
            canPlay = true;
            break;
    }

    if (am.isWiredHeadsetOn()) {
        canPlay = true;
    }

    if (canPlay) {

        try {
            Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            String path = AttachFile.getFilePathFromUri(alert);

            ringtonePlayer = new MediaPlayer();

            if (path == null) {
                ringtonePlayer.setDataSource(context, Uri.parse("android.resource://" + G.context.getPackageName() + "/" + R.raw.tone));
            } else {
                ringtonePlayer.setDataSource(G.context, alert);
            }

            if (am.isWiredHeadsetOn()) {
                ringtonePlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
            } else {
                ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
            }

            ringtonePlayer.setLooping(true);
            ringtonePlayer.prepare();
            ringtonePlayer.start();
        } catch (Exception e) {
            HelperLog.setErrorLog("activity call view model   set ringtone uri  " + e);
        }
    }

    startRingAnimation();
}