欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

一起学Android之音频视频

程序员文章站 2022-06-03 19:05:36
本文演示了如何通过Api播放音频和视频文件,来获得良好性能和愉快的用户体验,仅供学习分享使用,如有不足之处,还请指正。 ......

概述

android多媒体框架支持各种常见的媒体类型,可以很容易地将音频、视频和图像集成到app中。通过mediaplayer api,可以从应用程序资源(raw)、文件系统或网络上数据流资源来播放音频或视频。本文演示了如何通过api播放音频和视频文件,来获得良好性能和愉快的用户体验,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

  1.  mediaplayer 可以用来控制audio/video文件或流播放的类。通过此类,可以方便的控制音频/视频文件的播放,暂停和停止等操作。
  2. uri 统一资源标识符(uniform resource identifier,或uri)是一个用于标识某一互联网资源名称的字符串。
  3. videoview 自带的一种播放视频的组件。
  4. surfaceview 可以通过后台绘制显示的视图组件。 

activity中播放音频

 页面上播放音频文件,步骤如下:

1. 准备资源文件,并播放

 1 private mediaplayer mmediaplayer;
 2 
 3     /**
 4      * 开始
 5      * @param v
 6      */
 7     public void bn_start(view v){
 8         if(mmediaplayer==null) {
 9             ready();
10         }
11         mmediaplayer.start();
12     }
13 
14  /**
15      * 创建mediaplayer并到prepare状态
16      */
17     private void ready(){
18         if(mmediaplayer==null){
19             mmediaplayer=new mediaplayer();//idle
20             //log.i("tag", "ready: "+filepath);
21             file file=new file(environment.getexternalstoragedirectory(),"goldfallen.mp3");
22             log.i("tag", "ready: "+file.getpath());
23             log.i("tag", "ready: "+file.exists());
24             uri uri= uri.fromfile(file);
25             try {
26                 mmediaplayer.setdatasource(audioactivity.this,uri);
27                 mmediaplayer.prepare();//prepared
28             } catch (ioexception e) {
29                 log.i("tag", "ready: "+ e.getmessage());
30                 e.printstacktrace();
31             }
32         }
33     }

2. 暂停播放

1 /**
2      * 暂停
3      * @param v
4      */
5     public void bn_pause(view v){
6         if(mmediaplayer!=null && mmediaplayer.isplaying()){
7             mmediaplayer.pause();
8         }
9     }

3. 停止

 1   /**
 2      * 停止
 3      * @param v
 4      */
 5     public void bn_stop(view v){
 6         if(mmediaplayer!=null && mmediaplayer.isplaying()){
 7             mmediaplayer.stop();
 8             mmediaplayer.release();
 9             mmediaplayer=null;
10         }
11     }

4. 释放资源(当页面销毁时,播放资源也要同时释放)

1  @override
2     protected void ondestroy() {
3         if(mmediaplayer!=null && mmediaplayer.isplaying()){
4             mmediaplayer.stop();
5             mmediaplayer.release();
6             mmediaplayer=null;
7         }
8         super.ondestroy();
9     }

5. 通过静态函数创建对象

 1 /**
 2      * d:\android\project\demomedia\app\src\main\res\raw\a2012.mp3:
 3      * error: 'a' is not a valid file-based resource name character:
 4      * file-based resource names must contain only lowercase a-z, 0-9, or underscore
 5      */
 6     private void ready2(){
 7         if(mmediaplayer==null){
 8             mmediaplayer= mediaplayer.create(this,r.raw.ab2012);
 9         }
10     }

通过服务来播放音频

当页面关闭时,音频文件还可以在后台播放。步骤如下:

1. 定义后台服务,当服务启动时,创建mediaplayer对象,并注册服务接收对象。

 1 public class audioservice extends service {
 2 
 3     private mediaplayer mmediaplayer;
 4 
 5     private operatorreceiver mreceiver;
 6 
 7     public audioservice() {
 8     }
 9 
10     @override
11     public void oncreate() {
12         super.oncreate();
13         mmediaplayer=new mediaplayer();
14         mreceiver=new operatorreceiver();
15         intentfilter filter=new intentfilter("operator.receiver");
16         registerreceiver(mreceiver,filter);
17     }
18 
19     @override
20     public ibinder onbind(intent intent) {
21         return null;
22     }
23 
24     @override
25     public int onstartcommand(intent intent, int flags, int startid) {
26         log.i("tag", "onstartcommand: ----ready ");
27         ready();
28         return super.onstartcommand(intent, flags, startid);
29     }
30 
31     @override
32     public void ondestroy() {
33         if(mmediaplayer!=null && mmediaplayer.isplaying()){
34             mmediaplayer.stop();
35         }
36         if(mmediaplayer!=null){
37             mmediaplayer.release();
38             mmediaplayer=null;
39         }
40         unregisterreceiver(mreceiver);
41         super.ondestroy();
42     }
43 
44     private void start(){
45         mmediaplayer.start();
46     }
47 
48     private  void pause(){
49         mmediaplayer.pause();
50     }
51 
52     private void stop(){
53         mmediaplayer.stop();
54         ready();
55     }
56 
57     private void ready(){
58         mmediaplayer.reset();
59         try {
60             string filepath= environment.getexternalstoragedirectory()+"/ab2012.mp3";
61             log.i("tag", "ready: "+filepath);
62             file file=new file(filepath);
63             if(file.exists()) {
64                 mmediaplayer.setdatasource(filepath);
65                 mmediaplayer.prepare();
66             }else{
67                 log.i("tag", "ready: 文件不存在 ");
68             }
69         } catch (ioexception e) {
70             log.i("tag", "ready: "+e.getmessage());
71             e.printstacktrace();
72         }
73     }
74 }

2. 操作接收者定义如下:

 1  /**
 2      * 操作接收器
 3      */
 4     class operatorreceiver extends broadcastreceiver
 5     {
 6         @override
 7         public void onreceive(context context, intent intent) {
 8             int cmd=intent.getintextra("cmd",-1);
 9             log.i("tag", "onreceive: "+cmd);
10             switch (cmd){
11                 case tools.play:
12                     start();
13                     break;
14                 case tools.pause:
15                     pause();
16                     break;
17                 case tools.stop:
18                     stop();
19                     break;
20                 default:
21                     start();
22                     break;
23 
24             }
25         }
26     }

3. 启动服务

1   intent intent =new intent(this,audioservice.class);
2   startservice(intent);

4. 前台activity通过发送广播命令进行控制音频的播放与暂停

 1 /**
 2      * 开始
 3      * @param v
 4      */
 5     public void bn_start(view v){
 6         intent intent=new intent("operator.receiver");
 7         intent.putextra("cmd",tools.play);
 8         sendbroadcast(intent);
 9         log.i("tag", "bn_start: "+"service");
10     }
11 
12     /**
13      * 暂停
14      * @param v
15      */
16     public void bn_pause(view v){
17         intent intent=new intent("operator.receiver");
18         intent.putextra("cmd",tools.pause);
19         sendbroadcast(intent);
20     }
21 
22     /**
23      * 停止
24      * @param v
25      */
26     public void bn_stop(view v){
27         intent intent=new intent("operator.receiver");
28         intent.putextra("cmd",tools.stop);
29         sendbroadcast(intent);
30     }

5.通过后台服务的方式,需要在androidmanifest.xml文件中进行注册

1  <service
2             android:name=".audioservice"
3             android:enabled="true"
4             android:exported="true">
5         </service>

通过videoview来播放视频

 通过videoview进行播放视频文件,只需要设置资源uri即可,具体如下:

 1  private videoview mvideoview;
 2     @override
 3     protected void oncreate(bundle savedinstancestate) {
 4         super.oncreate(savedinstancestate);
 5         setcontentview(r.layout.activity_video);
 6         mvideoview= (videoview) this.findviewbyid(r.id.vv_info);
 7         //设置路径
 8         file file=new file(environment.getexternalstoragedirectory(),"dcim/camera/vid20190629142614.mp4");
 9         log.i("tag", "oncreate: "+file.getpath());
10         if(!file.exists()){
11             log.i("tag", "oncreate: 文件不存在");
12         }
13         uri uri=uri.fromfile(file);
14         mvideoview.setvideouri(uri);
15         //设置media controller
16         mediacontroller controller=new mediacontroller(this);
17         mvideoview.setmediacontroller(controller);
18         //获取焦点
19         mvideoview.requestfocus();
20         mvideoview.start();
21         //设置播放完成事件
22         mvideoview.setoncompletionlistener(new mediaplayer.oncompletionlistener() {
23             @override
24             public void oncompletion(mediaplayer mp) {
25                 toast.maketext(videoactivity.this, "播放完毕", toast.length_short).show();
26             }
27         });
28     }

通过mediaplayer来播放视频

通过mediaplayer来播放视频文件,然后通过surfaceview来显示视频内容,具体步骤如下:

1.启动,通过setdisplay来设置显示内容

 1 public  void bn_start(view view)  {
 2         mmediaplayer.reset();//到idle状态
 3         //设置路径
 4         file file=new file(environment.getexternalstoragedirectory(),"dcim/camera/vid20190629142614.mp4");
 5         log.i("tag", "oncreate: "+file.getpath());
 6         if(!file.exists()){
 7             log.i("tag", "oncreate: 文件不存在");
 8         } else {
 9             log.i("tag", "oncreate: 文件存在 ");
10         }
11         uri uri=uri.fromfile(file);
12         try {
13             mmediaplayer.setdatasource(this,uri);
14             mmediaplayer.setdisplay(msurfaceview.getholder());
15             mmediaplayer.prepare();
16             mmediaplayer.start();
17         } catch (ioexception e) {
18             e.printstacktrace();
19         }
20     }

2. 暂停与停止

 1  public  void bn_pause(view view){
 2         if(mmediaplayer.isplaying()){
 3             mmediaplayer.pause();
 4         }
 5     }
 6 
 7     public  void bn_stop(view view){
 8         if(mmediaplayer.isplaying()){
 9             mmediaplayer.stop();
10         }
11     }

3. 资源释放

 1  @override
 2     protected void ondestroy() {
 3         if(mmediaplayer!=null && mmediaplayer.isplaying()){
 4             mmediaplayer.stop();
 5         }
 6         if(mmediaplayer!=null){
 7             mmediaplayer.release();
 8             mmediaplayer=null;
 9         }
10         super.ondestroy();
11     }

权限设置

如果要播放视频,需要相应的权限设置,并在安装时获取请求权限

1     <uses-permission android:name="android.permission.internet"/>
2     <uses-permission android:name="android.permission.write_external_storage"/>
3     <uses-permission android:name="android.permission.read_external_storage"/>
4     <uses-permission android:name="android.permission.mount_unmount_filesystems"/>

备注

合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下。