天天看點

22_Android中的本地音樂播放器和網絡音樂播放器的編寫,本地視訊播放器和網絡視訊播放器,照相機案例,偷拍案例實作

1 編寫以下案例:

22_Android中的本地音樂播放器和網絡音樂播放器的編寫,本地視訊播放器和網絡視訊播放器,照相機案例,偷拍案例實作

當點選了”播放”之後,在手機上的/mnt/sdcard2/natural.mp3就會播放。

2 編寫布局檔案activity_main.xml

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".mainactivity" >

    <edittext

        android:id="@+id/et_path"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="請輸入要播放檔案的路徑" />

    <linearlayout

        android:layout_width="match_parent"

        android:orientation="horizontal" >

        <button

            android:id="@+id/bt_play"

            android:onclick="play"

            android:layout_width="0dip"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="播放" />

              android:id="@+id/bt_pause"

            android:onclick="pause"

            android:text="暫停" />

              android:id="@+id/bt_stop"

            android:onclick="stop"

            android:text="停止" />

              android:id="@+id/bt_replay"

            android:onclick="replay"

            android:text="重播" />

    </linearlayout>

</linearlayout>

3 編寫mainactivity

package com.itheima.musicplayer;

import java.io.file;

import java.io.ioexception;

import android.app.activity;

import android.media.audiomanager;

import android.media.mediaplayer;

import android.media.mediaplayer.oncompletionlistener;

import android.os.bundle;

import android.view.view;

import android.widget.button;

import android.widget.edittext;

import android.widget.toast;

public class mainactivity extends activity {

    private edittext et_path;

    private mediaplayer mediaplayer;

    private button bt_play,bt_pause,bt_stop,bt_replay;

    @override

    protected void oncreate(bundle savedinstancestate) {

       super.oncreate(savedinstancestate);

       setcontentview(r.layout.activity_main);

       et_path = (edittext) findviewbyid(r.id.et_path);

       bt_play = (button) findviewbyid(r.id.bt_play);

       bt_pause = (button) findviewbyid(r.id.bt_pause);

       bt_stop = (button) findviewbyid(r.id.bt_stop);

       bt_replay = (button) findviewbyid(r.id.bt_replay);

    }

    /**

     * 播放

     * @param view

     */

    public void play(view view) {

       string filepath = et_path.gettext().tostring().trim();

       file file = new file(filepath);

       if(file.exists()){

           try {

              mediaplayer = new mediaplayer();

              mediaplayer.setdatasource(filepath);//設定播放的資料源。

               mediaplayer.setaudiostreamtype(audiomanager.stream_music);

              mediaplayer.prepare();//準備開始播放 播放的邏輯是c代碼在新的線程裡面執行。

              mediaplayer.start();

              bt_play.setenabled(false);

              mediaplayer.setoncompletionlistener(new oncompletionlistener() {

                  @override

                  public void oncompletion(mediaplayer mp) {

                     bt_play.setenabled(true);

                  }

              });

           } catch (exception e) {

              e.printstacktrace();

              toast.maketext(this, "播放失敗", 0).show();

           }

       }else{

           toast.maketext(this, "檔案不存在,請檢查檔案的路徑", 0).show();

       }

     * 暫停

    public void pause(view view) {

       if("繼續".equals(bt_pause.gettext().tostring())){

           mediaplayer.start();

           bt_pause.settext("暫停");

           return;

       if(mediaplayer!=null&&mediaplayer.isplaying()){

           //這裡表示的是暫停功能

           mediaplayer.pause();

           bt_pause.settext("繼續");

     * 停止

    public void stop(view view) {

           //通過stop方法停止播放音樂

           mediaplayer.stop();

           mediaplayer.release();

           mediaplayer = null;

       bt_pause.settext("暫停");

       bt_play.setenabled(true);

     * 重播

    public void replay(view view) {

           //通過seekto方法指定到某個位置播放音樂

           mediaplayer.seekto(0);

           play(view);

}

如果想播放網絡上的音樂,需要把上面的play代碼改成:

/**

     *

       // http://

       if (filepath.startswith("http://")) {

              mediaplayer.setdatasource(filepath);// 設定播放的資料源。

              // mediaplayer.prepare();//同步的準備方法。

              mediaplayer.prepareasync();// 異步的準備

              mediaplayer.setonpreparedlistener(new onpreparedlistener() {

                  public void onprepared(mediaplayer mp) {

                     mediaplayer.start();

                     bt_play.setenabled(false);

        } else {

           toast.maketext(this, "請檢查檔案的路徑", 0).show();

==============================================================================

視訊播放器,實作”播放”、“暫停”、”停止”、“重播”。案例截圖如下:

22_Android中的本地音樂播放器和網絡音樂播放器的編寫,本地視訊播放器和網絡視訊播放器,照相機案例,偷拍案例實作

播放布局檔案

    <seekbar

        android:id="@+id/seekbar1"

        android:layout_height="wrap_content" />

            android:text="播放" />

            android:id="@+id/bt_pause"

            android:text="暫停" />

            android:id="@+id/bt_stop"

            android:text="停止" />

            android:id="@+id/bt_replay"

            android:text="重播" />

    <surfaceview

        android:id="@+id/sv"

        android:layout_height="fill_parent" />

編寫mainactivity,代碼如下:

import java.util.timer;

import java.util.timertask;

import android.view.surfaceholder;

import android.view.surfaceholder.callback;

import android.view.surfaceview;

import android.widget.seekbar;

import android.widget.seekbar.onseekbarchangelistener;

    private surfaceview sv;

    private surfaceholder holder;

    private int position;

    private string filepath;

    private seekbar seekbar1;

    private timer timer;

    private timertask task;

       seekbar1 = (seekbar) findviewbyid(r.id.seekbar1);

       seekbar1.setonseekbarchangelistener(new onseekbarchangelistener() {

           @override

           public void onstoptrackingtouch(seekbar seekbar) {

              int postion = seekbar.getprogress();

              mediaplayer.seekto(postion);

           public void onstarttrackingtouch(seekbar seekbar) {

           public void onprogresschanged(seekbar seekbar, int progress,

                  boolean fromuser) {

       });

       //得到surfaceview

       sv = (surfaceview) findviewbyid(r.id.sv);

       //得到顯示界面内容的容器

       holder = sv.getholder();

       //在低版本模拟器上運作記得加上下面的參數。不自己維護雙緩沖區,而是等待多媒體播放架構主動的推送資料。

       holder.settype(surfaceholder.surface_type_push_buffers);

       holder.addcallback(new callback() {

           public void surfacedestroyed(surfaceholder holder) {

              system.out.println("destoryed");

              if(mediaplayer!=null&&mediaplayer.isplaying()){

                  position = mediaplayer.getcurrentposition();

                  mediaplayer.stop();

                  mediaplayer.release();

                  mediaplayer = null;

                  timer.cancel();

                  task.cancel();

                  timer = null;

                  task = null;

              }

           public void surfacecreated(surfaceholder holder) {

              system.out.println("created");

              if(position>0){//記錄的有播放進度。

                  try {

                     mediaplayer = new mediaplayer();

                     mediaplayer.setdatasource(filepath);//設定播放的資料源。

                      mediaplayer.setaudiostreamtype(audiomanager.stream_music);

                     mediaplayer.setdisplay(holder);

                     mediaplayer.prepare();//準備開始播放 播放的邏輯是c代碼在新的線程裡面執行。

                     mediaplayer.seekto(position);

                     mediaplayer.setoncompletionlistener(new oncompletionlistener() {

                         @override

                         public void oncompletion(mediaplayer mp) {

                            bt_play.setenabled(true);

                         }

                     });

                     int max = mediaplayer.getduration();

                     seekbar1.setmax(max);

                     timer = new timer();

                     task = new timertask() {

                         public void run() {

                             seekbar1.setprogress(mediaplayer.getcurrentposition());

                     };

                     timer.schedule(task, 0, 500);

                  } catch (ioexception e) {

                     e.printstacktrace();

           public void surfacechanged(surfaceholder holder, int format, int width,

                  int height) {

              system.out.println("changed");

       filepath = et_path.gettext().tostring().trim();

              mediaplayer.setdisplay(holder);

              //設定拖動進度條的最大值

              int max = mediaplayer.getduration();

              seekbar1.setmax(max);

              timer = new timer();

              task = new timertask() {

                  public void run() {

                      seekbar1.setprogress(mediaplayer.getcurrentposition());

              };

              timer.schedule(task, 0, 500);

網絡視訊播放器,編寫布局檔案

        android:hint="請輸入要播放檔案的路徑"/>

編寫mainactivity

       //file file = new file(filepath);

       if(filepath.startswith("http://")){

               mediaplayer.setdatasource(filepath);//設定播放的資料源。

androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.itheima.musicplayer"

    android:versioncode="1"

    android:versionname="1.0" >

    <uses-sdk

        android:minsdkversion="8"

        android:targetsdkversion="19" />

    <!-- 注意如果涉及到網絡的都要添加上下面的一句 -->

    <uses-permission android:name="android.permission.internet"/>

    <application

        android:allowbackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/apptheme" >

        <activity

            android:name="com.itheima.musicplayer.mainactivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.main" />

                <category android:name="android.intent.category.launcher" />

            </intent-filter>

        </activity>

    </application>

</manifest>

照相機引用,如果想使用模拟器進行拍照,需要制定模拟器的一個設定,設定如下圖:

22_Android中的本地音樂播放器和網絡音樂播放器的編寫,本地視訊播放器和網絡視訊播放器,照相機案例,偷拍案例實作

編寫以下案例,當點選”拍照”之後彈出權限提示框。

22_Android中的本地音樂播放器和網絡音樂播放器的編寫,本地視訊播放器和網絡視訊播放器,照相機案例,偷拍案例實作

1 編寫布局檔案activity_main.xml,代碼如下:

    <button

        android:onclick="click"

        android:text="拍照" />

    <imageview

        android:layout_width="wrap_content"

        android:id="@+id/iv"/>

1 mainactivity的代碼如下:

package com.itheima.camera;

import android.content.intent;

import android.net.uri;

import android.os.environment;

import android.provider.mediastore;

import android.util.log;

import android.widget.imageview;

 * 拍照的執行個體代碼

 * @author toto

 */

public class mainactivity extends activity {

         private imageview iv;

         private file file;

         @override

         protected void oncreate(bundle savedinstancestate) {

                   super.oncreate(savedinstancestate);

                   setcontentview(r.layout.activity_main);

                   iv = (imageview) findviewbyid(r.id.iv);

         }

         /**

          * 當點選之後的效果

          * @param view

          */

         public void click(view view) {

                   intent intent = new intent();

                   //指定拍照的意圖action_image_capture,如果是錄像的可以用action_video_capture,并且将檔案字尾改成.3gp

                   intent.setaction(mediastore.action_image_capture);

                   log.i("file-path", environment.getexternalstoragedirectory().tostring());

                   //第一個參數是檔案路徑,第二個參數表示的是檔案名稱

                   file =  new file(environment.getexternalstoragedirectory(),system.currenttimemillis()+".jpg");

                   //指定儲存檔案的路徑

                   intent.putextra(mediastore.extra_output, uri.fromfile(file));

                   //開啟一個新的action,并且獲得其傳回值

                   startactivityforresult(intent, 100);

          * 當startactivityforresult傳回結果的時候會執行下面的函數

         protected void onactivityresult(int requestcode, int resultcode, intent data) {

                   if (resultcode == 100) {

                            iv.setimageuri(uri.fromfile(file));

                   }

                   super.onactivityresult(requestcode, resultcode, data);

若是手機,例如我的手機,存儲在/sdcard/emulated/0中。

===============================================================================

偷拍的案例,編寫如下案例(将下面的圖檔顯示區域變得很小可以實作偷拍功能):

22_Android中的本地音樂播放器和網絡音樂播放器的編寫,本地視訊播放器和網絡視訊播放器,照相機案例,偷拍案例實作

1 編寫布局檔案activity_main.xml

        android:text="拍照"/>

    <framelayout

         android:id="@+id/camera_preview"

         android:layout_width="100dip"

         android:layout_height="100dip"/>

2 camerapreview的代碼如下:

package com.itheima.camera2;

import android.content.context;

import android.hardware.camera;

/** a basic camera preview class */

public class camerapreview extends surfaceview implements surfaceholder.callback {

    private static final string tag = "camerapreview";

    private surfaceholder mholder;

    private camera mcamera;

    @suppresswarnings("deprecation")

    public camerapreview(context context, camera camera) {

        super(context);

        mcamera = camera;

        // install a surfaceholder.callback so we get notified when the

        // underlying surface is created and destroyed.

        mholder = getholder();

        mholder.addcallback(this);

        // deprecated setting, but required on android versions prior to 3.0

        mholder.settype(surfaceholder.surface_type_push_buffers);

    public void surfacecreated(surfaceholder holder) {

        // the surface has been created, now tell the camera where to draw the preview.

        try {

            mcamera.setpreviewdisplay(holder);

            mcamera.startpreview();

        } catch (ioexception e) {

            log.d(tag, "error setting camera preview: " + e.getmessage());

        }

    public void surfacedestroyed(surfaceholder holder) {

        // empty. take care of releasing the camera preview in your activity.

    public void surfacechanged(surfaceholder holder, int format, int w, int h) {

        // if your preview can change or rotate, take care of those events here.

        // make sure to stop the preview before resizing or reformatting it.

        if (mholder.getsurface() == null){

          // preview surface does not exist

          return;

        // stop preview before making changes

        try {

            mcamera.stoppreview();

        } catch (exception e){

          // ignore: tried to stop a non-existent preview

        // set preview size and make any resize, rotate or

        // reformatting changes here

        // start preview with new settings

            mcamera.setpreviewdisplay(mholder);

            log.d(tag, "error starting camera preview: " + e.getmessage());

mainactivity的代碼如下:

import java.io.fileoutputstream;

import android.hardware.camera.autofocuscallback;

import android.hardware.camera.picturecallback;

import android.os.systemclock;

import android.widget.framelayout;

    private imageview iv;

    private camerapreview mpreview;

       iv = (imageview) findviewbyid(r.id.iv);

        // create an instance of camera

        mcamera = getcamerainstance();

        // create our preview view and set it as the content of our activity.

        mpreview = new camerapreview(this, mcamera);

        framelayout preview = (framelayout) findviewbyid(r.id.camera_preview);

        preview.addview(mpreview);

    public void click(view view){

       mcamera.autofocus(new autofocuscallback() {

           public void onautofocus(boolean success, camera camera) {

              mcamera.takepicture(null, null, new picturecallback() {

                  public void onpicturetaken(byte[] data, camera camera) {

                     try {

                         //file file = new file(environment.getexternalstoragedirectory(),systemclock.uptimemillis()+".jpg");

                         file file = new file("/mnt/sdcard2",systemclock.uptimemillis()+".jpg");

                         fileoutputstream fos = new fileoutputstream(file);

                         fos.write(data);

                         fos.close();

                         toast.maketext(getapplicationcontext(), "成功", 0).show();

                         mcamera.startpreview();

                     } catch (exception e) {

                         e.printstacktrace();

                     }

    /** 擷取一個照相機執行個體 */

    public static camera getcamerainstance(){

        camera c = null;

        try {

            c = camera.open(); // attempt to get a camera instance

        }

        catch (exception e){

            // camera is not available (in use or does not exist)

        return c; // returns null if camera is unavailable

    protected void ondestroy() {

       mcamera.stoppreview();

       mcamera.release();

       mcamera = null;

       super.ondestroy();

編寫androidmanifest.xml的清單檔案,代碼如下:

    package="com.itheima.camera2"

   <uses-permission android:name="android.permission.camera" />

    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.write_external_storage" />

            android:name="com.itheima.camera2.mainactivity"



繼續閱讀