Example usage for android.media MediaPlayer MediaPlayer

List of usage examples for android.media MediaPlayer MediaPlayer

Introduction

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

Prototype

public MediaPlayer() 

Source Link

Document

Default constructor.

Usage

From source file:nuclei.media.playback.FallbackPlayback.java

/**
 * Makes sure the media player exists and has been reset. This will create
 * the media player if needed, or reset the existing media player if one
 * already exists./* w  w w  .j av  a2 s . c  o m*/
 */
private void createMediaPlayerIfNeeded() {
    mPrepared = false;
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();

        // Make sure the media player will acquire a wake-lock while
        // playing. If we don't do that, the CPU might go to sleep while the
        // song is playing, causing playback to stop.
        mMediaPlayer.setWakeMode(mService.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing,
        // and when it's done playing:
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnSeekCompleteListener(this);
    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.novemser.voicetest.ui.MainActivity.java

/**
 * mp3// w ww.  j  a v  a 2 s  . c  o  m
 *
 * @return
 */
public MediaPlayer createNetMp3(String url) {
    MediaPlayer mp = new MediaPlayer();
    try {
        mp.setDataSource(url);
    } catch (IllegalArgumentException e) {
        return null;
    } catch (IllegalStateException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
    return mp;
}

From source file:dk.ciid.android.infobooth.activities.SubscriptionFinalActivity.java

private void initMediaPlayer() {
    String PATH_TO_FILE = voice6;
    mediaPlayer = new MediaPlayer();

    try {/*from  w  w w  . j  a  v a  2 s  . c o  m*/
        mediaPlayer.setDataSource(PATH_TO_FILE);
        mediaPlayer.prepare();
        if (isInDebugMode)
            Toast.makeText(this, PATH_TO_FILE, Toast.LENGTH_LONG).show();
        stateMediaPlayer = stateMP_NotStarter;
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        stateMediaPlayer = stateMP_Error;
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        stateMediaPlayer = stateMP_Error;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        stateMediaPlayer = stateMP_Error;
    }
}

From source file:com.intel.xdk.player.Player.java

public void startAudio(String strRelativeFileURL, boolean shouldLoop) {
    if (isPlayingPodcast()) {
        injectJS(//from   ww w .  j  a  v  a2s  .  co  m
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.busy',true,true);document.dispatchEvent(ev);");
        return;
    } else if (isPlayingAudio()) {
        stopAudio();
    }

    soundName = strRelativeFileURL;
    Object path = pathToFile(strRelativeFileURL);

    try {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
        } catch (Exception e) {
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setLooping(shouldLoop);
        mediaPlayer.setOnErrorListener(soundOnError);
        mediaPlayer.setOnCompletionListener(soundOnComplete);

        //set data source based on type
        if (path instanceof AssetFileDescriptor) {
            try {
                AssetFileDescriptor afd = ((AssetFileDescriptor) path);
                mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            File file = new File((String) path);
            try {
                FileInputStream fis = new FileInputStream(file);
                mediaPlayer.setDataSource(fis.getFD());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        mediaPlayer.prepare();
        mediaPlayer.seekTo(audioTime);
        mediaPlayer.setVolume(audioVolume, audioVolume);
        mediaPlayer.start();
    } catch (Exception e) {
        injectJS(
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.error',true,true);document.dispatchEvent(ev);");
        return;
    }

    //activity.trackPageView("/intel.xdk.podcast." + getAudioName(soundName) + ".stop");

    setPlayingAudio(true);
    injectJS(
            "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.start');document.dispatchEvent(ev);");
}

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

private void playBeep(boolean error) {

    if (!isAdded()) {
        return;/*  w  ww  . ja va 2s.  c  o m*/
    }

    try {
        MediaPlayer beepPlayer = new MediaPlayer();

        String file = "beep.mp3";

        if (error) {
            file = "error.mp3";
        }

        AssetFileDescriptor descriptor = context.getAssets().openFd(file);
        beepPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(),
                descriptor.getLength());
        descriptor.close();

        beepPlayer.prepare();

        beepPlayer.start();
    } catch (Exception io) {
        //We'll manage without the beep :)
    }
}

From source file:com.visva.voicerecorder.utils.Utils.java

public static long getDurationTimeFromFile(String filePath) {
    if (StringUtility.isEmpty(filePath)) {
        AIOLog.e(MyCallRecorderConstant.TAG, "filePath is null");
        return 0;
    }//from  w  w w.  j  a  va  2  s.c om
    File file = new File(filePath);
    if (file == null || !file.exists()) {
        Log.d("KieuThang", "file it not exitsted!");
    }
    MediaPlayer mediaPlayer = new MediaPlayer();
    long duration = 0L;
    try {
        mediaPlayer.setDataSource(filePath);
        mediaPlayer.prepare();
        duration = mediaPlayer.getDuration();
        mediaPlayer.reset();
        mediaPlayer.release();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //the valid time we offer to save at least more than 1s
    if (duration > 1000) {
        AIOLog.d(MyCallRecorderConstant.TAG, "InValid time:" + duration);
        return duration;
    }
    AIOLog.d(MyCallRecorderConstant.TAG, "Valid time:" + duration);
    return 0;
}

From source file:jupiter.broadcasting.live.holo.JBPlayer.java

public void StartPlayBackground(String path) throws IOException {
    Progress(true);//w ww . jav a 2  s  .  c  o  m
    if (mVideoCastManager.isConnected()) {
        //casting
        String[] tit_ep;
        tit_ep = title.split("[|]");
        MediaMetadata mMediaMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
        mMediaMetadata.putString(MediaMetadata.KEY_TITLE, live ? title : tit_ep[0]);
        mMediaMetadata.putString(MediaMetadata.KEY_SUBTITLE, live ? "streaming" : tit_ep[1]);
        mMediaMetadata.putString(MediaMetadata.KEY_STUDIO, "Jupiter Broadcasting");
        mMediaMetadata.addImage(new WebImage(Uri
                .parse(null == pic ? "http://jb4.cdn.scaleengine.net/wp-content/themes/jb2014/images/logo.png"
                        : pic)));
        //the second only for the controller page
        mMediaMetadata.addImage(new WebImage(Uri
                .parse(null == pic ? "http://jb4.cdn.scaleengine.net/wp-content/themes/jb2014/images/logo.png"
                        : pic)));
        MediaInfo mSelectedMedia = new MediaInfo.Builder(path).setContentType("audio/mp3")
                .setStreamType(live ? MediaInfo.STREAM_TYPE_LIVE : MediaInfo.STREAM_TYPE_BUFFERED)
                .setMetadata(mMediaMetadata).build();
        Progress(false);
        mVideoCastManager.startCastControllerActivity(this, mSelectedMedia, 0, true);
    } else {
        //local playback
        play.setEnabled(false);
        start = true;
        mediaController = new MediaController(this);
        mp = new MediaPlayer();
        mp.setDataSource(path);
        mp.prepareAsync();
        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer player) {
                mp.start();
                Toast.makeText(getBaseContext(), "Started", Toast.LENGTH_LONG).show();
                Progress(false);
                iView.setVisibility(View.GONE);
            }
        });
        mediaController.setMediaPlayer(this);
        mediaController.setAnchorView(findViewById(R.id.jbplayer));
        mediaController.setEnabled(true);
        mediaController.show();
    }
}

From source file:com.wojtechnology.sunami.TheBrain.java

private void init() {
    mSongManager = new SongManager(this);
    mGenreGraph = new GenreGraph(this);
    mSongHistory = new SongHistory(HISTORY_SIZE);
    mShuffleController = new ShuffleController(this, mGenreGraph, mSongManager, mUpNext);
    mMediaPlayer = new MediaPlayer();

    // Setting wake locks
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
    mWakeLock.acquire();// ww  w.  j a  v a2 s. c  o  m

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if (!mPreparing) {
                playNext();
            }
        }
    });
    mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            return false;
        }
    });
    mMediaPlayer.setOnPreparedListener(mMPPreparedListener);
    mContext.setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:com.insthub.O2OMobile.Activity.C1_PublishOrderActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.c1_publish_order);
    mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    File file = new File(newFileName());
    if (file.exists()) {
        file.delete();/*from  w w  w  . j  a  va 2  s.c  om*/
    }

    Intent intent = getIntent();
    mServiceType = (SERVICE_TYPE) intent.getSerializableExtra(O2OMobileAppConst.SERVICE_TYPE);
    mDefaultReceiverId = intent.getIntExtra(DEFAULT_RECEIVER_ID, 0);
    service_list = intent.getStringExtra("service_list");

    mBack = (ImageView) findViewById(R.id.top_view_back);
    mTitle = (TextView) findViewById(R.id.top_view_title);
    mBack.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
        }
    });
    mArrowImage = (ImageView) findViewById(R.id.top_view_arrow_image);
    mClose = (ImageView) findViewById(R.id.top_view_right_close);
    mTitleView = (LinearLayout) findViewById(R.id.top_view_title_view);
    mServiceTypeView = (FrameLayout) findViewById(R.id.c1_publish_order_service_type_view);
    mServiceTypeListview = (ListView) findViewById(R.id.c1_publish_order_service_type_list);
    mPrice = (EditText) findViewById(R.id.c1_publish_order_price);
    mTime = (TextView) findViewById(R.id.c1_publish_order_time);
    mLocation = (EditText) findViewById(R.id.c1_publish_order_location);
    mText = (EditText) findViewById(R.id.c1_publish_order_text);
    mVoice = (Button) findViewById(R.id.c1_publish_order_voice);
    mVoicePlay = (Button) findViewById(R.id.c1_publish_order_voicePlay);
    mVoiceReset = (ImageView) findViewById(R.id.c1_publish_order_voiceReset);
    mPublish = (Button) findViewById(R.id.c1_publish_order_publish);
    mVoiceView = (FrameLayout) findViewById(R.id.c1_publish_order_voice_view);
    mVoiceAnim = (ImageView) findViewById(R.id.c1_publish_order_voice_anim);
    mVoiceAnim.setImageResource(R.anim.voice_animation);
    mAnimationDrawable = (AnimationDrawable) mVoiceAnim.getDrawable();
    mAnimationDrawable.setOneShot(false);
    mTitleView.setEnabled(false);
    mServiceTypeView.setOnClickListener(null);
    mServiceTypeListview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            if (mDefaultReceiverId == 0) {
                mTitle.setText(mHomeModel.publicServiceTypeList.get(position).title);
                mServiceTypeId = mHomeModel.publicServiceTypeList.get(position).id;
                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(C1_PublishOrderActivity.this,
                        mHomeModel.publicServiceTypeList, position);
                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            } else {
                mTitle.setText(mServiceTypeList.get(position).title);
                mServiceTypeId = mServiceTypeList.get(position).id;
                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(C1_PublishOrderActivity.this,
                        mServiceTypeList, position);
                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            }

        }
    });

    mTitleView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (mServiceTypeView.getVisibility() == View.GONE) {
                mServiceTypeView.setVisibility(View.VISIBLE);
                mClose.setVisibility(View.VISIBLE);
                mArrowImage.setImageResource(R.drawable.b4_arrow_up);
                AnimationUtil.showAnimationFromTop(mServiceTypeListview);
                closeKeyBoard();
            } else {
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            }
        }
    });

    mClose.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mClose.setVisibility(View.GONE);
            mArrowImage.setImageResource(R.drawable.b3_arrow_down);
            AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
            Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    mServiceTypeView.setVisibility(View.GONE);
                }
            };
            mHandler.sendEmptyMessageDelayed(0, 200);
        }
    });

    mPrice.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            if (s.toString().length() > 0) {
                if (s.toString().substring(0, 1).equals(".")) {
                    s = s.toString().substring(1, s.length());
                    mPrice.setText(s);
                }
            }
            if (s.toString().length() > 1) {
                if (s.toString().substring(0, 1).equals("0")) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        s = s.toString().substring(1, s.length());
                        mPrice.setText(s);
                        CharSequence charSequencePirce = mPrice.getText();
                        if (charSequencePirce instanceof Spannable) {
                            Spannable spanText = (Spannable) charSequencePirce;
                            Selection.setSelection(spanText, charSequencePirce.length());
                        }
                    }
                }
            }
            boolean flag = false;
            for (int i = 0; i < s.toString().length() - 1; i++) {
                String getstr = s.toString().substring(i, i + 1);
                if (getstr.equals(".")) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                int i = s.toString().indexOf(".");
                if (s.toString().length() - 3 > i) {
                    String getstr = s.toString().substring(0, i + 3);
                    mPrice.setText(getstr);
                    CharSequence charSequencePirce = mPrice.getText();
                    if (charSequencePirce instanceof Spannable) {
                        Spannable spanText = (Spannable) charSequencePirce;
                        Selection.setSelection(spanText, charSequencePirce.length());
                    }
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    initData();

    mHomeModel = new HomeModel(this);
    mHomeModel.addResponseListener(this);
    if (mDefaultReceiverId == 0) {
        mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
        mHomeData = mShared.getString("home_data", "");
        if ("".equals(mHomeData)) {
            mHomeModel.getServiceTypeList();
        } else {
            try {
                servicetypelistResponse response = new servicetypelistResponse();
                response.fromJson(new JSONObject(mHomeData));
                mHomeModel.publicServiceTypeList = response.services;
                setServiceTypeAdater();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (service_list != null && !"".equals(service_list)) {
            try {
                JSONObject userJson = new JSONObject(service_list);
                myservicelistResponse response = new myservicelistResponse();
                response.fromJson(userJson);
                for (int i = 0; i < response.services.size(); i++) {
                    SERVICE_TYPE service = new SERVICE_TYPE();
                    service = response.services.get(i).service_type;
                    mServiceTypeList.add(service);
                }
                if (mServiceTypeList.size() > 0) {
                    mTitleView.setEnabled(true);
                    mArrowImage.setVisibility(View.VISIBLE);
                    if (mServiceType != null) {
                        for (int i = 0; i < mServiceTypeList.size(); i++) {
                            if (mServiceType.id == mServiceTypeList.get(i).id) {
                                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(this, mServiceTypeList, i);
                                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                                mTitle.setText(mServiceTypeList.get(i).title);
                                mServiceTypeId = mServiceTypeList.get(i).id;
                                break;
                            }
                        }
                    } else {
                        mC1PublishOrderAdapter = new C1_PublishOrderAdapter(this, mServiceTypeList);
                        mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                        mTitle.setText(getString(R.string.select_service));
                    }

                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
            mHomeData = mShared.getString("home_data", "");
            if ("".equals(mHomeData)) {
                mHomeModel.getServiceTypeList();
            } else {
                try {
                    servicetypelistResponse response = new servicetypelistResponse();
                    response.fromJson(new JSONObject(mHomeData));
                    mHomeModel.publicServiceTypeList = response.services;
                    setServiceTypeAdater();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    mLocationInfoModel = new LocationInfoModel(this);
    mLocationInfoModel.addResponseListener(this);
    mLocationInfoModel.get();

    mOrderPublishModel = new OrderPublishModel(this);
    mOrderPublishModel.addResponseListener(this);

    //??
    CharSequence charSequencePirce = mPrice.getText();
    if (charSequencePirce instanceof Spannable) {
        Spannable spanText = (Spannable) charSequencePirce;
        Selection.setSelection(spanText, charSequencePirce.length());
    }
    CharSequence charSequenceLocation = mLocation.getText();
    if (charSequenceLocation instanceof Spannable) {
        Spannable spanText = (Spannable) charSequenceLocation;
        Selection.setSelection(spanText, charSequenceLocation.length());
    }

    mVoice.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                closeKeyBoard();
                mVoice.setKeepScreenOn(true);
                mMaxTime = MAX_TIME;
                mVoiceView.setVisibility(View.VISIBLE);
                mAnimationDrawable.start();
                startRecording();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mVoice.setKeepScreenOn(false);
                mVoiceView.setVisibility(View.GONE);
                mAnimationDrawable.stop();
                if (mMaxTime > 28) {
                    mVoice.setEnabled(false);
                    Handler mHandler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            stopRecording();
                            mVoice.setEnabled(true);
                        }
                    };
                    mHandler.sendEmptyMessageDelayed(0, 500);
                } else {
                    stopRecording();
                }
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                mVoice.setKeepScreenOn(false);
                mVoiceView.setVisibility(View.GONE);
                mAnimationDrawable.stop();
                if (mMaxTime > 28) {
                    mVoice.setEnabled(false);
                    Handler mHandler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            stopRecording();
                            mVoice.setEnabled(true);
                        }
                    };
                    mHandler.sendEmptyMessageDelayed(0, 500);
                } else {
                    stopRecording();
                }
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                mVoice.getParent().requestDisallowInterceptTouchEvent(true);
            }
            return false;
        }
    });

    mVoicePlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mPlayer == null) {
                File file = new File(mFileName);
                if (file.exists()) {
                    mPlayer = new MediaPlayer();
                    mVoicePlay.setBackgroundResource(R.anim.record_animation);
                    mAnimationDrawable2 = (AnimationDrawable) mVoicePlay.getBackground();
                    mAnimationDrawable2.setOneShot(false);
                    mAnimationDrawable2.start();
                    try {
                        mPlayer.setDataSource(mFileName);
                        mPlayer.prepare();
                        mPlayer.start();
                        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                mp.reset();
                                mPlayer = null;
                                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                                mAnimationDrawable2.stop();
                            }
                        });
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(C1_PublishOrderActivity.this, getString(R.string.file_does_not_exist),
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                mPlayer.release();
                mPlayer = null;
                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                mAnimationDrawable2.stop();
            }
        }
    });

    mVoiceReset.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mPlayer != null) {
                mPlayer.release();
                mPlayer = null;
                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                mAnimationDrawable2.stop();
            }
            File file = new File(mFileName);
            if (file.exists()) {
                file.delete();
            }
            mVoice.setVisibility(View.VISIBLE);
            mVoicePlay.setVisibility(View.GONE);
            mVoiceReset.setVisibility(View.GONE);
        }
    });

    mPublish.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            File file = new File(newFileName());
            int duration = 0;
            if (file.exists()) {
                MediaPlayer mp = MediaPlayer.create(C1_PublishOrderActivity.this, Uri.parse(mFileName));
                if (null != mp) {
                    duration = mp.getDuration();//? ms
                    mp.release();
                }
                if (duration % 1000 > 500) {
                    duration = duration / 1000 + 1;
                } else {
                    duration = duration / 1000;
                }
            } else {
                file = null;
            }
            int num = 0;
            try { // ??
                Date date = new Date();
                Date date1 = mFormat.parse(mFormat.format(date));
                Date date2 = mFormat.parse(mTime.getText().toString());
                num = date2.compareTo(date1);

                if (num < 0) {
                    long diff = date1.getTime() - date2.getTime();
                    long mins = diff / (1000 * 60);
                    if (mins < 3) {
                        num = 1;
                    }
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (mServiceTypeId == 0) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.select_service));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mPrice.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.price_range));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mPrice.getText().toString().equals("0.")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.right_price));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mTime.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.appoint_time));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (num < 0) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.wrong_appoint_time_hint));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mLocation.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.appoint_location_hint));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else {
                mOrderPublishModel.publish(mPrice.getText().toString(), mTime.getText().toString(),
                        mLocation.getText().toString(), mText.getText().toString(), file, mServiceTypeId,
                        mDefaultReceiverId, duration);
            }
        }
    });
}

From source file:com.hhunj.hhudata.ForegroundService.java

private MediaPlayer ring() throws Exception, IOException {

    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    MediaPlayer player = new MediaPlayer();

    player.setDataSource(this, alert);

    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {

        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

        player.setLooping(true);/*from  ww w.  j  a  v  a 2  s .  c o  m*/

        player.prepare();

        player.start();

    }

    return player;

}