1 编写以下案例:
当点击了”播放”之后,在手机上的/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();
==============================================================================
视频播放器,实现”播放”、“暂停”、”停止”、“重播”。案例截图如下:
播放布局文件
<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>
照相机引用,如果想使用模拟器进行拍照,需要制定模拟器的一个设置,设置如下图:
编写以下案例,当点击”拍照”之后弹出权限提示框。
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中。
===============================================================================
偷拍的案例,编写如下案例(将下面的图片显示区域变得很小可以实现偷拍功能):
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"