/** * 播放 * * @param position */ private void start(int position) { this.currentPosition = position; isError = false; String url = null; if (getUrlList() != null && getUrlList().size() > 0) { url = getUrlList().get(position); } if (getInfoList() != null && getInfoList().size() > 0) { currentInfo.setText(getInfoList().get(position)); } if (mPlayer != null && url != null) { try { mPlayer.setDataSource(url); mSurface.requestLayout(); requestLayout(); mPlayer.prepareAsync(); isPrepare = true; showFlow(); } catch (IllegalArgumentException | IOException | IllegalStateException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public void play(int position) { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } currentPodcastInPlayer = position; play(); }
public void prepare() throws IOException { if (mVideoResources.size() <= 0) return; VideoResource first = mVideoResources.get(0); mTagsContainer.setVideoTags(first.getVideoTags()); mActiveMediaPlayer.setDataSource(getContext(), first.getVideoUri()); mActiveMediaPlayer.prepare(); }
public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub try { msurfaceholder.setFixedSize(getPictureWidth(), getPictureHeight()); int progress = 0; progress = getSavedProgress(); if (progress > 0) { mmediaplayer.seekTo(progress); sendMsg(VideoConst.MSG_SEEKING); mPlayStatus = VideoConst.PLAY_STATUS_SEEKING; } else { mmediaplayer.start(); sendMsg(VideoConst.MSG_PLAY_START); mPlayStatus = VideoConst.PLAY_STATUS_STARTED; if (mOnPBPreparedListener != null) { mOnPBPreparedListener.onPrepared(pb); } } if (previewMode == true) { setPreviewRect(); } } catch (Exception e) { try { throw new Exception(e); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
void setSelected(Cursor c) { Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; long newId = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)); mSelectedUri = ContentUris.withAppendedId(uri, newId); mSelectedId = newId; if (newId != mPlayingId || mMediaPlayer == null) { stopMediaPlayer(); mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(this, mSelectedUri); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.prepare(); mMediaPlayer.start(); mPlayingId = newId; } catch (IOException e) { MusicLogUtils.e(TAG, "Unable to play track", e); /// M: finally just get invalidate list view @{ } finally { getListView().invalidateViews(); } /// @} } else if (mMediaPlayer != null) { stopMediaPlayer(); getListView().invalidateViews(); } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.linear); btplay = (Button) findViewById(R.id.bttocar); btpausar = (Button) findViewById(R.id.btpausar); Player = MediaPlayer.create(this, R.raw.a); try { Player.prepare(); } catch (Exception e) { } btplay.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View arg0) { Player.start(); } }); btpausar.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View arg0) { Player.pause(); } }); }
public void onPrepared(MediaPlayer mp) { mCurrentState = STATE_PREPARED; // modify by lxj // Get the capabilities of the player for this stream // Metadata data = mp.getMetadata(MediaPlayer.METADATA_ALL, // MediaPlayer.BYPASS_METADATA_FILTER); // // if (data != null) { // mCanPause = !data.has(Metadata.PAUSE_AVAILABLE) // || data.getBoolean(Metadata.PAUSE_AVAILABLE); // mCanSeekBack = !data.has(Metadata.SEEK_BACKWARD_AVAILABLE) // || data.getBoolean(Metadata.SEEK_BACKWARD_AVAILABLE); // mCanSeekForward = !data.has(Metadata.SEEK_FORWARD_AVAILABLE) // || data.getBoolean(Metadata.SEEK_FORWARD_AVAILABLE); // } else { // mCanPause = mCanSeekBack = mCanSeekForward = true; // } mCanPause = mCanSeekBack = mCanSeekForward = true; if (mOnPreparedListener != null) { mOnPreparedListener.onPrepared(mMediaPlayer); } if (mMediaController != null) { mMediaController.setEnabled(true); } mVideoWidth = mp.getVideoWidth(); mVideoHeight = mp.getVideoHeight(); int seekToPosition = mSeekWhenPrepared; // mSeekWhenPrepared may be changed after seekTo() call if (seekToPosition != 0) { seekTo(seekToPosition); } if (mVideoWidth != 0 && mVideoHeight != 0) { // Log.i("@@@@", "video size: " + mVideoWidth +"/"+ mVideoHeight); getHolder().setFixedSize(mVideoWidth, mVideoHeight); if (mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) { // We didn't actually change the size (it was already at the size // we need), so we won't get a "surface changed" callback, so // start the video here instead of in the callback. if (mTargetState == STATE_PLAYING) { start(); if (mMediaController != null) { mMediaController.show(); } } else if (!isPlaying() && (seekToPosition != 0 || getCurrentPosition() > 0)) { if (mMediaController != null) { // Show the media controls when we're paused into a video and make 'em stick. mMediaController.show(0); } } } } else { // We don't know the video size yet, but should start anyway. // The video size might be reported to us later. if (mTargetState == STATE_PLAYING) { start(); } } }
@Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); // Log.i("tvinfo", msg.what + "-" + msg.obj); if (msg.what == 1) { progress.setVisibility(View.VISIBLE); title.setText("开始播放 ..."); } if (msg.what == 2) { title.setText("开始加载 ..."); } if (msg.what == 3) { title.setText("开始播放 ..."); play(prg); } if (msg.what == 4) { title.setText("加载失败 ..."); } if (msg.what == 9) { show("获取", "正在获取播放列表,请稍后..."); } if (msg.what == -100) { playmenu.setVisibility(View.GONE); } if (msg.what == 66) { if (player != null && player.isPlaying() && !isseek) { currtime.setText(Utils.longToString(player.getCurrentPosition())); playSeek.setProgress(player.getCurrentPosition() / 1000); } } }
public static void stop(Context context) { if (mp != null) { mp.stop(); mp.release(); mp = null; } }
/** * create mediaplayer for music * * @param pPath the pPath relative to assets * @return */ private MediaPlayer createMediaplayer(final String path) { MediaPlayer mediaPlayer = new MediaPlayer(); try { if (CocosPlayClient.isEnabled() && !CocosPlayClient.isDemo()) { CocosPlayClient.updateAssets(path); } CocosPlayClient.notifyFileLoaded(path); if (path.startsWith("/")) { final FileInputStream fis = new FileInputStream(path); mediaPlayer.setDataSource(fis.getFD()); fis.close(); } else { final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(path); mediaPlayer.setDataSource( assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); } mediaPlayer.prepare(); mediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume); } catch (final Exception e) { mediaPlayer = null; Log.e(Cocos2dxMusic.TAG, "error: " + e.getMessage(), e); } return mediaPlayer; }
private void notifyUser() { if (!sound) return; Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(500); if (player == null) player = MediaPlayer.create(this, R.raw.dice); player.start(); }
private void initData(Context context) { this.mContext = context; mActivity = (Activity) context; DisplayMetrics dm = new DisplayMetrics(); mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm); mDensity = dm.density; mWidth = dm.widthPixels; mInflater = LayoutInflater.from(mContext); AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.MODE_NORMAL); if (audioManager.isSpeakerphoneOn()) { audioManager.setSpeakerphoneOn(true); } else { audioManager.setSpeakerphoneOn(false); } mp.setAudioStreamType(AudioManager.STREAM_RING); mp.setOnErrorListener( new OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { return false; } }); }
@Override public void play() { if (mMediaPlayer.getCurrentPosition() >= mMediaPlayer.getDuration()) { mMediaPlayer.seekTo(0); } mMediaPlayer.start(); }
/** 停止播放 */ public void stopPlayer() { if (mPlayer != null) { mPlayer.stop(); mPlayer.release(); mPlayer = null; } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome); /** 开启欢迎界面延时3秒进入主界面 */ // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // Intent intent=new Intent(Welcome.this,MainInterface.class); // Welcome.this.startActivity(intent); // Welcome.this.finish(); // } // },delayTime); /** 在欢迎界面的同时播放“听音乐用酷我” */ mediaPlayer = MediaPlayer.create(this, R.raw.kuwo); mediaPlayer.start(); /** 跳过广告按钮 */ findViewById(R.id.btnStart) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Welcome.this, MainInterface.class)); } }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainActivity = this; requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置全屏 getWindow() .setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); DisplayMetrics metric = new DisplayMetrics(); // 获取屏幕高度、宽度 getWindowManager().getDefaultDisplay().getMetrics(metric); windowHeight = metric.heightPixels; // 屏幕高度 windowWidth = metric.widthPixels; // 屏幕宽度 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); res = getResources(); // 加载main.xml界面设计文件 setContentView(R.layout.main); // 获取main.xml界面设计文件中ID为mainLayout的组件 mainLayout = (FrameLayout) findViewById(R.id.mainLayout); // 创建GameView组件 mainView = new GameView(this.getApplicationContext(), GameView.STAGE_INIT); mainLP = new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT); mainLayout.addView(mainView, mainLP); // 播放背景音乐 player = MediaPlayer.create(this, R.raw.background); player.setLooping(true); player.start(); }
/** This method runs at a fixed rate. */ @Override public void run() { switch (mState) { case PREPARED: mState = BellRepeaterState.PLAYING; mMediaPlayer.start(); Log.i("BellRepeater", "Media player starting"); break; case PLAYING: // Restart the tone // mState remains PLAYING mMediaPlayer.seekTo(0); Log.i("BellRepeater", "Media player restarting"); break; case STOPPED: // In theory this shouldn't happen, because the timer should be cancelled. // But just in case, do nothing. return; default: break; } // If it's not the last repetition, set the completion listener to change the state to // PREPARED, so that on the next run() we know to use start() rather than seekTo(). if (++mRepetitionsSoFar < mBellInfo.getTimesToPlay()) { mMediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mState = BellRepeaterState.PREPARED; Log.i("BellRepeater", "Media player completed"); } }); // If it's the last repetition, set the completion listener to release the player and // change the state to FINISHED, and cancel the timer (i.e. clean everything up). } else { mMediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // The MediaPlayer coming here should be the same one as mMediaPlayer in the // BellRepeater class if (mp != mMediaPlayer) { Log.e( this.getClass().getSimpleName(), "OnCompletionListener mp wasn't the same as mMediaPlayer!"); } mMediaPlayer.release(); mMediaPlayer = null; mState = BellRepeaterState.FINISHED; Log.i("BellRepeater", "Over and out"); } }); mTimer.cancel(); } }
private void createPlayerView() { mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView); mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mMediaPlayer = new MediaPlayer(); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setOnPreparedListener( new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { startPlaying(); } }); mMediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // 自动播放下一个 mMediaPlayer.reset(); playNext(); } }); }
public static void Setup() { String musicDir = Environment.getExternalStorageDirectory().getAbsolutePath() + MUSIC_DIR; mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(musicDir); mediaPlayer.prepare(); mediaPlayer.setLooping(true); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 构造方法 * * @param context */ public MusicPlayer(Context context) { this.context = context; // File file = new File(filePath); // if(!file.exists()){ // Timber.e("文件不存在!!!"); // } // 初始化 mediaPlayer = MediaPlayer.create(context, R.raw.test); // mediaPlayer.setLooping(true); // mediaPlayer.prepare(); // 设置监听器 mediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Timber.e("complete"); } }); mediaPlayer.setOnErrorListener( new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Timber.e("error"); return false; } }); }
/** pause */ public void pause() throws IllegalStateException { if (mmediaplayer != null) { if (mPlayStatus == VideoConst.PLAY_STATUS_STARTED) { try { mmediaplayer.pause(); } catch (IllegalStateException e) { e.printStackTrace(); sendMsg(VideoConst.MSG_INVALID_STATE); throw new IllegalStateException(e); } mPlayStatus = VideoConst.PLAY_STATUS_PAUSED; MmpTool.LOG_DBG("pause!"); } else { try { mmediaplayer.start(); } catch (IllegalStateException e) { e.printStackTrace(); sendMsg(VideoConst.MSG_INVALID_STATE); throw new IllegalStateException(e); } mPlayStatus = VideoConst.PLAY_STATUS_STARTED; MmpTool.LOG_DBG("play!"); } } }
public void setFileState(int state) { switch (state) { case 0: m_mediaPlayer.pause(); break; case 1: m_mediaPlayer.stop(); try { m_mediaPlayer.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } m_mediaPlayer.seekTo(0); break; case 2: case 3: m_mediaPlayer.start(); break; default: break; } }
public void stop() { try { if (mp != null) { if (mp.isPlaying() || isPaused()) { if (DBG) { Log.d(LCAT, "audio is playing, stop()"); } setState(STATE_STOPPING); mp.stop(); setState(STATE_STOPPED); if (remote) { stopProgressTimer(); } try { mp.prepare(); } catch (IOException e) { Log.e(LCAT, "Error while preparing audio after stop(). Ignoring."); } catch (IllegalStateException e) { Log.w(LCAT, "Error while preparing audio after stop(). Ignoring."); } } if (isPaused()) { paused = false; } } } catch (Throwable t) { Log.e(LCAT, "Error : ", t); } }
/** 设置闹铃 */ private void setAlarm() { alarmMusic = MediaPlayer.create(this, R.raw.a); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM); current = mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); String key = entry.getKey(); try { if (clockModel.getRing().equals(key)) { alarmMusic = MediaPlayer.create(this, map.get(key)); } } catch (Exception e) { alarmMusic = MediaPlayer.create(this, R.raw.a); } } // 设置为循环播放 alarmMusic.setLooping(true); // 获取震动 mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE); // 震动时长与音乐播放时长一样,放在MediaPlayer.create()之后,不然报错null object reference // mVibrator.vibrate(alarmMusic.getDuration()); mVibrator.vibrate(new long[] {1000, 2000, 1000, 2000, 1000}, 0); // 调节到最大音量 mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, max, AudioManager.FLAG_PLAY_SOUND); // 闹铃响 alarmMusic.start(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pear); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // player mMediaPlayer = MediaPlayer.create(this, R.raw.pear); mMediaPlayer.start(); // object for the speaker sound sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); soundID = sound.load(this, R.raw.pear, 1); // object for the check sound click = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); soundID = click.load(this, R.raw.click, 1); // letters findViewById(R.id.pear_p).setOnTouchListener(this); findViewById(R.id.pear_e).setOnTouchListener(this); findViewById(R.id.pear_a).setOnTouchListener(this); findViewById(R.id.pear_r).setOnTouchListener(this); // bottom containers drag listener findViewById(R.id.bottom_p).setOnDragListener(this); findViewById(R.id.bottom_e).setOnDragListener(this); findViewById(R.id.bottom_a).setOnDragListener(this); findViewById(R.id.bottom_r).setOnDragListener(this); // top container drag listener findViewById(R.id.top_c).setOnDragListener(this); }
private void playTrue() { setEnable(false); final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.true_false_1 + new Random().nextInt(4)); mediaPlayer.setOnPreparedListener( new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mediaPlayer.start(); new Handler() .postDelayed( new Runnable() { @Override public void run() { mediaPlayer.release(); setEnable(true); ask(); } }, mediaPlayer.getDuration()); } }); }
private void tryToRestoreLocation() { try { if (location == null) { return; } boolean found = false; for (int i = 0; i < metaHolder.getSize(); i++) { if (metaHolder.get(i).getTitle().equals(location.title)) { currentPodcastInPlayer = i; found = true; break; } } if (!found) { location = null; return; } mediaPlayer.reset(); mediaPlayer.setDataSource(currentFile().toString()); mediaPlayer.prepare(); mediaPlayer.seekTo(currentMeta().getCurrentPos()); mediaMode = MediaMode.Paused; } catch (Throwable e) { // bummer. } }
@Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub float[] values = event.values; float x = values[0]; float y = values[1]; float z = values[2]; Log.i("uri", "x轴方向的重力加速度" + x + ";y轴方向的重力加速度" + y + ";z轴方向的重力加速度" + z); // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。 int medumValue = 18; if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) { id_text.setText("屌丝男士"); try { player.start(); player.setOnCompletionListener( new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub player.pause(); player.seekTo(0); } }); } catch (Exception e) { e.printStackTrace(); } vibrator.vibrate(500); Message msg = new Message(); msg.what = SENSOR_SHAKE; handler.sendMessage(msg); } }
private void playFile() { if (playingFile == null || !playingFile.isFile()) resetPlayingFile(); if (playingFile == null) { Toast.makeText(AndroidWave.this, "Cannot play file", Toast.LENGTH_SHORT).show(); return; } if (mp != null) mp.stop(); Log.d("file to play", playingFile.getAbsolutePath()); mp = MediaPlayer.create(AndroidWave.this, Uri.fromFile(playingFile)); if (mp == null) { Toast.makeText(AndroidWave.this, "Cannot play file", Toast.LENGTH_SHORT).show(); return; } mp.setOnCompletionListener( new OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg0) { stopPlayFile(); } }); sm.stop(); mp.start(); playButton.setText(R.string.stop); playButton.setBackgroundColor(0xFF009900); }
@Override public void onPrepared(MediaPlayer mp) { if (isPrepare) { if (playType == PLAY_TYPE_LOD || playType == PLAY_TYPE_ONDEMAND) { // TODO 数据库操作 记忆续播 MPConPlayManager cPm = MPConPlayUtils.findConnectionPlay(currentPosition, parentName, getChildName()); if (cPm != null && cPm.getEpisodePos() == currentPosition && cPm.getPlayIndex() != 0) { mp.seekTo(cPm.getPlayIndex()); } mHandler.sendEmptyMessage(SHOW_CONTROL_ANIMATION); } mp.start(); isPrepare = false; if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); } // 判断是否是本地播放或在线点播 if (playType == PLAY_TYPE_LOD || playType == PLAY_TYPE_ONDEMAND) { if (mp.isPlaying() && !mSeekBar.isPressed()) { mHandler.sendEmptyMessage(UPDATA_PLAY_TIME); } } mProgressBar.setVisibility(View.INVISIBLE); mPlayer.setScreenOnWhilePlaying(true); } }