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

android MediaRecorder实现录屏时带录音功能

程序员文章站 2022-06-19 21:08:31
下面说说android的事把最近是不是也会遇到需求中需要用到录屏录音的功能,最近也是遇到的 现在整理完记录一下首先呢,录音录屏需要权限 先贴一个动态权限类public class talallow {...

下面说说android的事把

最近是不是也会遇到需求中需要用到录屏录音的功能,最近也是遇到的 现在整理完记录一下

首先呢,录音录屏需要权限 先贴一个动态权限类

public class talallow {
  /**
   * record_audio     音频权限
   * write_external_storage 写入权限
   * camera        相机权限
   */
  public static void requestpermissions(context context,int allowcode) {
    arraylist<string> ps = new arraylist<>();
    int per = contextcompat.checkselfpermission(context, manifest.permission.record_audio);
    if (per != packagemanager.permission_granted) {
      ps.add(manifest.permission.record_audio);
    }
    per = contextcompat.checkselfpermission(context, manifest.permission.write_external_storage);
    if (per != packagemanager.permission_granted) {
      ps.add(manifest.permission.write_external_storage);
    }
    per = contextcompat.checkselfpermission(context, manifest.permission.camera);
    if (per != packagemanager.permission_granted) {
      ps.add(manifest.permission.camera);
    }
    per = contextcompat.checkselfpermission(context, manifest.permission.read_phone_state);
    if (per != packagemanager.permission_granted) {
      ps.add(manifest.permission.read_phone_state);
    }
    log.d(tag, "requestpermissions:ps=" + ps.size());
    if (!ps.isempty()) {
      string[] ps3 = new string[ps.size()];
      ps.toarray(ps3);
      activitycompat.requestpermissions((activity) context, ps3, allowcode);
    }
  }
}

有需求需要判断权限的呢 插入个链接 (上面那个类code码为100)
判断是否有权限

下面重点来了

首先说明一下这个录屏和录音是在服务里面做的,所以呢贴一个服务类
这个代码绝对有质量 做了很多处理,下面一行一行解读把

//首先呢实现的是handle.callback接口 主要是做时间及计时时间回调的,会重新写handlemessage方法,其实我个觉得跟在括号{} 里面重写没啥区别就是简洁页面
public class talscreenrecordservice extends service implements handler.callback {
//这个就不解释了吧 log
  private static final string tag = "talscreenrecordservice";
  //这个类是管理类拿到服务后会通过下面的类申请录屏,点击允许,
  //其中会回调两个参数,code码 和 data,都在activityforresult中进行判断code
  private mediaprojectionmanager mprojectionmanager;
 //这个会拿到申请的结果
  private mediaprojection mmediaprojection;
  //这个类就是我们主要的录屏录音的类啦
  private mediarecorder mmediarecorder;
  //这个就是我们要获取录制屏幕的大小,像素,等等一些数据
  //关于这类更详细的介绍https://blog.csdn.net/qq_16628781/article/details/62038163
  private virtualdisplay mvirtualdisplay;
 //是否正在录制 false 没有录制
  private boolean misrunning;
  //获取屏幕的宽高和像素密度 稍后贴类
  private int mrecordwidth = talscreenparams.getscreenwidth();
  private int mrecordheight = talscreenparams.getscreenwidth();
  private int mscreendpi = talscreenparams.getscreendpi();
 //code data 就是上面说的允许后回调
  private int mresultcode;
  private intent mresultdata;
  //录屏文件的保存地址
  private string mrecordfilepath;
  private handler mhandler;
  //已经录制多少秒了
  private int mrecordseconds = 0;
  //handle发送消息时的what
  private static final int msg_type_count_down = 110;
 //这个是继承service 必须重写的方法 这是使用的bindservice(生命周期的长短跟activity一致)
  @override
  public ibinder onbind(intent intent) {
    return new recordbinder();
  }
 //说一说这个返回值的问题吧
 // start_sticky 粘性返回 ,一次失败,多次启动,不保留intent对象
 //关于返回值问题https://blog.csdn.net/github_37663523/article/details/78811539
 @override
  public int onstartcommand(intent intent, int flags, int startid) {
    return start_sticky;
  }
  @override
  public void oncreate() {
    super.oncreate();
    //没有录制
    misrunning = false;
    //创建对象 在create方法里只执行一次
    mmediarecorder = new mediarecorder();
    // 由于实现了callback接口,在这里注册一下接口(个人觉得高大的写法,简洁)
    mhandler = new handler(looper.getmainlooper(), this);
  }
  @override
  public void ondestroy() {
    super.ondestroy();
  }
 //数据不为空
  public boolean isready() {
    return mmediaprojection != null && mresultdata != null;
  }
 //清除的方法 避免内存泄漏 相信都看得懂
  @requiresapi(api = build.version_codes.lollipop)
  public void clearrecordelement() {
    clearall();
    if (mmediarecorder != null) {
      mmediarecorder.reset();
      mmediarecorder.release();
      mmediarecorder = null;
    }
    mresultdata = null;
    //不执行的时候false
    misrunning = false;
  }
 //这个就是给是否正在录屏提供一个get方法
  public boolean ismisrunning() {
    return misrunning;
  }
 //这个就是设置数据的方法在activityforresult中设置数据,说明是允许录屏的
  @targetapi(build.version_codes.lollipop)
  public void setresultdata(int resultcode, intent resultdata) {
    mresultcode = resultcode;
    mresultdata = resultdata;
 //拿到这个管理,看不懂跟上面注释结合看
    mprojectionmanager = (mediaprojectionmanager) getsystemservice(context.media_projection_service);
    //getmediaprojection(code,data)不知道这样写看不看的董 
    //说白了mediaprojectionmanager是申请权限 mediaprojection是获取申请结果,防止别人调取隐私
    //再通过上面的setresultdata方法获取到activityforresult中的code,data
    if (mprojectionmanager != null) {
      mmediaprojection = mprojectionmanager.getmediaprojection(mresultcode, mresultdata);
    }
  }
 //开始录制了
  @requiresapi(api = build.version_codes.lollipop)
  public boolean startrecord() {
  //代码执行顺序(false,目前没录屏)
    if (misrunning) {
      return false;
    }
    //再次创建,防止异常
    if (mmediaprojection == null) {
      mmediaprojection = mprojectionmanager.getmediaprojection(mresultcode, mresultdata);
    }
 //关于文件路径还有录屏的一些参数问题
    setupmediarecorder();
    //关于获取录制屏幕的大小,像素,等等一些数据
    createvirtualdisplay();
    //开始录制
    mmediarecorder.start();
 //稍后贴类 监听录制情况
    talscreenutils.startrecord();
    //最多录制三分钟
    mhandler.sendemptymessagedelayed(msg_type_count_down, 1000);
    //录制时为true
    misrunning = true;
    log.d(tag, "startrecord ");
    return true;
  }
 //停止的方法
  @requiresapi(api = build.version_codes.lollipop)
  public boolean stoprecord(string tip) {
    log.d(tag, "stoprecord: first ");
    //misrunning 默认值为false !misrunning 就是true。。
    if (!misrunning) {
      return false;
    }
    misrunning = false;
    log.w(tag, "stoprecord middle");
    try {
    //停止抓取异常,该置空的为空
      mmediarecorder.stop();
      mmediarecorder.reset();
      mmediarecorder = null;
      mvirtualdisplay.release();
      mmediaprojection.stop();
      log.w(tag, "stoprecord ");
    } catch (exception e) {
      e.printstacktrace();
      mmediarecorder.release();
      mmediarecorder = null;
      log.w(tag, "stoprecord exception");
    }
    mmediaprojection = null;
 //停止时移出这条消息what 
    mhandler.removemessages(msg_type_count_down);
    //停止的监听 tip 是处理一些突发情况 比如内存不足
    talscreenutils.stoprecord(tip);
    log.i(tag, "stoprecord: " + mrecordfilepath);
    //录制时间不到两秒就删除录制文件
    if (mrecordseconds <= 2) {
      talfileutils.deletesdfile(mrecordfilepath);
    } else {
    //录制的视频库,将数据添加到媒体库
    //这个算是应用程序之间共享数据,把自己应用的数据添加到手机的媒体库contentresolver
    //举个例子,代码添加手机联系人到自己的联系人列表,或者代码添加图片到自己的图库,还有不懂得,贴个链接
    //https://blog.csdn.net/bzlj2912009596/article/details/80248272
      talfileutils.filescanvideo(this, mrecordfilepath, 1280, 720, mrecordseconds);
    }
//    mrecordfilepath = null;
    mrecordseconds = 0;
    return true;
  }
 //下面是关于处理在一些activity or fragment中生命周期的做法
  public void pauserecord() {
    if (mmediarecorder != null) {
      if (build.version.sdk_int >= build.version_codes.n) {
        mmediarecorder.pause();
      }
    }
  }
  public void resumerecord() {
    if (mmediarecorder != null) {
      if (build.version.sdk_int >= build.version_codes.n) {
        mmediarecorder.resume();
      }
    }
  }
 //这个就是刚才讲过的 绘制窗口大小,dpi问题 virtualdisplay
  @requiresapi(api = build.version_codes.lollipop)
  private void createvirtualdisplay() {
    mvirtualdisplay = mmediaprojection.createvirtualdisplay("mainscreen", 1280, 720, mscreendpi,
        displaymanager.virtual_display_flag_auto_mirror, mmediarecorder.getsurface(), null, null);
  }
 //这个主要是路径,还有设置一些录制视频参数问题separator 为字节,占位用
  @targetapi(build.version_codes.lollipop)
  private void setupmediarecorder() {
    mrecordfilepath = getsavedirectory() + file.separator + system.currenttimemillis() + ".mp4";
    log.i(tag, "setupmediarecorder: " + mrecordfilepath);
    if (mmediarecorder == null) {
      mmediarecorder = new mediarecorder();
    }
    //设置音频源
    mmediarecorder.setaudiosource(mediarecorder.audiosource.mic);
 //设置视频源    
    mmediarecorder.setvideosource(mediarecorder.videosource.surface);
 //设置输出的编码格式 
    mmediarecorder.setoutputformat(mediarecorder.outputformat.mpeg_4);
    if (mrecordfilepath != null) {
      mmediarecorder.setoutputfile(mrecordfilepath);
    } else if (mrecordfilepath == null) {
      mmediarecorder.setoutputfile(mrecordfilepath);
    }
    //设置录屏时屏幕大小,这个可跟mvirtualdisplay 一起控制屏幕大小
    //mvirtualdisplay 是将屏幕设置成多大多小,setvideosize是输出文件时屏幕多大多小
    mmediarecorder.setvideosize(1280, 720);
     //图像编码 h264较好还有其他选择
    mmediarecorder.setvideoencoder(mediarecorder.videoencoder.h264);
  //音频编码    
    mmediarecorder.setaudioencoder(mediarecorder.audioencoder.amr_nb);
    //设置码率 高清的话的要数越大
    mmediarecorder.setvideoencodingbitrate((int) (1280 * 720 * 2.6));
    //设置帧率,该帧率必须是硬件支持的,可以通过camera.cameraparameter.getsupportedpreviewfpsrange()方法获取相机支持的帧率
    mmediarecorder.setvideoframerate(20);
    try {
    //准备
      mmediarecorder.prepare();
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }
  @requiresapi(api = build.version_codes.lollipop)
  public void clearall() {
    if (mmediaprojection != null) {
      mmediaprojection.stop();
      mmediaprojection = null;
    }
  }
 //路径
  public string getrecordfilepath() {
    return mrecordfilepath;
  }
 //sd下绝对路径,先判断sd卡是否挂载
  public string getsavedirectory() {
    if (environment.getexternalstoragestate().equals(environment.media_mounted)) {
      return environment.getexternalstoragedirectory().getabsolutepath();
    } else {
      return null;
    }
  }
  //这是实现了handle.callback中重写方法 handlemessage
  @requiresapi(api = build.version_codes.lollipop)
  @override
  public boolean handlemessage(message msg) {
    switch (msg.what) {
      case msg_type_count_down: {
        string str = null;
        //这是内存
        boolean enough = talfileutils.getsdfreememory() / (1024 * 1024) < 4;
        if (enough) {
          //空间不足,停止录屏
          str = "空间不足";
          //停止录屏时 通过接口回调一个信息,是因为什么停止录屏的
          stoprecord(str);
          mrecordseconds = 0;
          break;
        }
        mrecordseconds++;
        int minute = 0, second = 0;
        if (mrecordseconds >= 60) {
          minute = mrecordseconds / 60;
          second = mrecordseconds % 60;
        } else {
          second = mrecordseconds;
        }
        talscreenutils.onrecording("0" + minute + ":" + (second < 10 ? "0" + second : second + ""));
        if (mrecordseconds < 5 * 60) {
          mhandler.sendemptymessagedelayed(msg_type_count_down, 1000);
        } else if (mrecordseconds == 5 * 60) {
          str = "录制已到限定时长";
          stoprecord(str);
          mrecordseconds = 0;
        }
        break;
      }
    }
    return true;
  }
  public class recordbinder extends binder {
    public talscreenrecordservice getrecordservice() {
      return talscreenrecordservice.this;
    }
  }
}

下面贴关于手机像素还有dpi的类

public class talscreenparams {
  private static int mscreenwidth;
  private static int mscreenheight;
  private static int mscreendpi;

  public static void init(activity activity){
    display display = activity.getwindowmanager().getdefaultdisplay();
    displaymetrics metrics = new displaymetrics();
    display.getmetrics(metrics);
    mscreenwidth = metrics.widthpixels;
    mscreenheight = metrics.heightpixels;
    mscreendpi = metrics.densitydpi;
  }

  public static int getscreenwidth(){
    return mscreenwidth;
  }

  public static int getscreenheight(){
    return mscreenheight;
  }

  public static int getscreendpi(){
    return mscreendpi;
  }

下面贴关于删除文件,添加到媒体库的类 这里就使用到了contentresolver

public class talfileutils {
  /**
   * 删除sd卡中的文件或目录
   *
   * @param path
   * @return
   */
  public static boolean deletesdfile(string path) {
    return deletesdfile(path, false);
  }

  /**
   * 删除sd卡中的文件或目录
   *
   * @param path
   * @param deleteparent true为删除父目录
   * @return
   */
  public static boolean deletesdfile(string path, boolean deleteparent) {
    if (textutils.isempty(path)) {
      return false;
    }

    file file = new file(path);
    if (!file.exists()) {
      //不存在
      return true;
    }
    return deletefile(file, deleteparent);
  }

  /**
   * @param file
   * @param deleteparent true为删除父目录
   * @return
   */
  public static boolean deletefile(file file, boolean deleteparent) {
    boolean flag = false;
    if (file == null) {
      return flag;
    }
    if (file.isdirectory()) {
      //是文件夹
      file[] files = file.listfiles();
      if (files.length > 0) {
        for (int i = 0; i < files.length; i++) {
          flag = deletefile(files[i], true);
          if (!flag) {
            return flag;
          }
        }
      }
      if (deleteparent) {
        flag = file.delete();
      }
    } else {
      flag = file.delete();
    }
    file = null;
    return flag;
  }

  /**
   * 添加到媒体数据库
   *
   * @param context 上下文
   */
  public static uri filescanvideo(context context, string videopath, int videowidth, int videoheight,
                  int videotime) {
    file file = new file(videopath);
    if (file.exists()) {
      uri uri = null;
      long size = file.length();
      string filename = file.getname();
      long datetaken = system.currenttimemillis();
      contentvalues values = new contentvalues(11);
      values.put(mediastore.video.media.data, videopath); // 路径;
      values.put(mediastore.video.media.title, filename); // 标题;
      values.put(mediastore.video.media.duration, videotime * 1000); // 时长
      values.put(mediastore.video.media.width, videowidth); // 视频宽
      values.put(mediastore.video.media.height, videoheight); // 视频高
      values.put(mediastore.video.media.size, size); // 视频大小;
      values.put(mediastore.video.media.date_taken, datetaken); // 插入时间;
      values.put(mediastore.video.media.display_name, filename);// 文件名;
      values.put(mediastore.video.media.date_modified, datetaken / 1000);// 修改时间;
      values.put(mediastore.video.media.date_added, datetaken / 1000); // 添加时间;
      values.put(mediastore.video.media.mime_type, "video/mp4");

      contentresolver resolver = context.getcontentresolver();

      if (resolver != null) {
        try {
          uri = resolver.insert(mediastore.video.media.external_content_uri, values);
        } catch (exception e) {
          e.printstacktrace();
          uri = null;
        }
      }

      if (uri == null) {
        mediascannerconnection.scanfile(context, new string[]{videopath}, new string[]{"video/*"}, new mediascannerconnection.onscancompletedlistener() {
          @override
          public void onscancompleted(string path, uri uri) {

          }
        });
      }

      return uri;
    }

    return null;
  }

  /**
   * sd卡存在并可以使用
   */
  public static boolean issdexists() {
    return environment.getexternalstoragestate().equals(
        environment.media_mounted);
  }

  /**
   * 获取sd卡的剩余容量,单位是byte
   *
   * @return
   */
  public static long getsdfreememory() {
    try {
      if (issdexists()) {
        file pathfile = environment.getexternalstoragedirectory();
        // retrieve overall information about the space on a filesystem.
        // this is a wrapper for unix statfs().
        statfs statfs = new statfs(pathfile.getpath());
        // 获取sdcard上每一个block的size
        long nblocksize = statfs.getblocksize();
        // 获取可供程序使用的block的数量
        // long navailblock = statfs.getavailableblockslong();
        long navailblock = statfs.getavailableblocks();
        // 计算sdcard剩余大小byte
        long nsdfreesize = navailblock * nblocksize;
        return nsdfreesize;
      }
    } catch (exception ex) {
      ex.printstacktrace();
    }
    return 0;
  }
  public static long getfreemem(context context) {
    activitymanager manager = (activitymanager) context.getapplicationcontext().getsystemservice(activity.activity_service);
    if (manager != null) {
      activitymanager.memoryinfo info = new activitymanager.memoryinfo();
      if (info != null) {
        manager.getmemoryinfo(info);
        // 单位byte
        return info.availmem / 1024 / 1024;
      }
    }
    return 0;
  }
}

还有一个类 是为整个service提供了便捷访问的类 ,将一些监听service中的变化放到集合里来做

public class talscreenutils {
  private static talscreenrecordservice s_screenrecordservice;
  private static list<recordlistener> s_recordlistener = new arraylist<>();
  private static list<onpagerecordlistener> s_pagerecordlistener = new arraylist<>();
  //true,录制结束的提示语正在显示
  public static boolean s_isrecordingtipshowing = false;
  /**
   * 录屏功能 5.0+ 的手机才能使用
   * @return
   */
  public static boolean isscreenrecordenable(){
    return build.version.sdk_int >= build.version_codes.lollipop ;
  }
  public static void setscreenservice(talscreenrecordservice screenservice){
    s_screenrecordservice = screenservice;
  }
  public static void clear(){
    if ( isscreenrecordenable() && s_screenrecordservice != null){
      s_screenrecordservice.clearall();
      s_screenrecordservice = null;
    }
    if (s_recordlistener != null && s_recordlistener.size() > 0){
      s_recordlistener.clear();
    }
    if (s_pagerecordlistener != null && s_pagerecordlistener.size() > 0 ){
      s_pagerecordlistener.clear();
    }
  }
  /**
   * 开始录制
   */
  public static void startscreenrecord(activity activity, int requestcode) {
    if (isscreenrecordenable()){
      if (s_screenrecordservice != null && !s_screenrecordservice.ismisrunning()){
        if (!s_screenrecordservice.isready()){
          mediaprojectionmanager mediaprojectionmanager = (mediaprojectionmanager) activity.
              getsystemservice(context.media_projection_service);
          if (mediaprojectionmanager != null){
            intent intent = mediaprojectionmanager.createscreencaptureintent();
            packagemanager packagemanager = activity.getpackagemanager();
            if (packagemanager.resolveactivity(intent,packagemanager.match_default_only) != null){
              //存在录屏授权的activity
              activity.startactivityforresult(intent,requestcode);
            }else {
              toast.maketext(activity, "不能录音", toast.length_short).show();
            }
          }
        } else {
          s_screenrecordservice.startrecord();
        }
      }
    }
  }
  /**
   * 获取用户允许录屏后,设置必要的数据
   * @param resultcode
   * @param resultdata
   */
  public static void setupdata(int resultcode,intent resultdata) throws exception{
    if (isscreenrecordenable()){
      if (s_screenrecordservice != null && !s_screenrecordservice.ismisrunning()){
        s_screenrecordservice.setresultdata(resultcode,resultdata);
        s_screenrecordservice.startrecord();
      }
    }
  }
  /**
   * 停止录制
   */
  public static void stopscreenrecord(context context){
    if (isscreenrecordenable()){
      if (s_screenrecordservice != null && s_screenrecordservice.ismisrunning()){
        string str = "停止录制";
        s_screenrecordservice.stoprecord(str);
      }
    }
  }
  /**
   * 获取录制后的文件地址
   * @return
   */
  public static string getscreenrecordfilepath(){
    if (isscreenrecordenable() && s_screenrecordservice!= null) {
      return s_screenrecordservice.getrecordfilepath();
    }
    return null;
  }
  /**
   * 判断当前是否在录制
   * @return
   */
  public static boolean iscurrentrecording(){
    if (isscreenrecordenable() && s_screenrecordservice!= null) {
      return s_screenrecordservice.ismisrunning();
    }
    return false;
  }
  /**
   * true,录制结束的提示语正在显示
   * @return
   */
  public static boolean isrecodingtipshow(){
    return s_isrecordingtipshowing;
  }
  public static void setrecordingstatus(boolean isshow){
    s_isrecordingtipshowing = isshow;
  }
  /**
   * 系统正在录屏,app 录屏会有冲突,清理掉一些数据
   */
  public static void clearrecordelement(){
    if (isscreenrecordenable()){
      if (s_screenrecordservice != null ){
        s_screenrecordservice.clearrecordelement();
      }
    }
  }
  public static void addrecordlistener(recordlistener listener){
    if (listener != null && !s_recordlistener.contains(listener)){
      s_recordlistener.add(listener);
    }
  }
  public static void removerecordlistener(recordlistener listener){
    if (listener != null && s_recordlistener.contains(listener)){
      s_recordlistener.remove(listener);
    }
  }
  public static void addpagerecordlistener( onpagerecordlistener listener){
    if (listener != null && !s_pagerecordlistener.contains(listener)){
      s_pagerecordlistener.add(listener);
    }
  }
  public static void removepagerecordlistener( onpagerecordlistener listener){
    if (listener != null && s_pagerecordlistener.contains(listener)){
      s_pagerecordlistener.remove(listener);
    }
  }
  public static void onpagerecordstart(){
    if (s_pagerecordlistener!= null && s_pagerecordlistener.size() > 0 ){
      for (onpagerecordlistener listener : s_pagerecordlistener){
        listener.onstartrecord();
      }
    }
  }
  public static void onpagerecordstop(){
    if (s_pagerecordlistener!= null && s_pagerecordlistener.size() > 0 ){
      for (onpagerecordlistener listener : s_pagerecordlistener){
        listener.onstoprecord();
      }
    }
  }
  public static void onpagebeforeshowanim(){
    if (s_pagerecordlistener!= null && s_pagerecordlistener.size() > 0 ){
      for (onpagerecordlistener listener : s_pagerecordlistener){
        listener.onbeforeshowanim();
      }
    }
  }
  public static void onpageafterhideanim(){
    if (s_pagerecordlistener!= null && s_pagerecordlistener.size() > 0 ){
      for (onpagerecordlistener listener : s_pagerecordlistener){
        listener.onafterhideanim();
      }
    }
  }
  public static void startrecord(){
    if (s_recordlistener.size() > 0 ){
      for (recordlistener listener : s_recordlistener){
        listener.onstartrecord();
        log.i("xxx", "startrecord: ");
      }
    }
  }
  public static void pauserecord(){
    if (s_recordlistener.size() > 0 ){
      for (recordlistener listener : s_recordlistener){
        listener.onpauserecord();
      }
    }
  }
  public static void resumerecord(){
    if (s_recordlistener.size() > 0 ){
      for (recordlistener listener : s_recordlistener){
        listener.onresumerecord();
      }
    }
  }
  public static void onrecording(string timetip){
    if (s_recordlistener.size() > 0 ){
      for (recordlistener listener : s_recordlistener){
        listener.onrecording(timetip);
      }
    }
  }
  public static void stoprecord(string stoptip){
    if (s_recordlistener.size() > 0 ){
      for (recordlistener listener : s_recordlistener){
        listener.onstoprecord( stoptip);
      }
    }
  }
  public interface recordlistener{
    void onstartrecord();
    void onpauserecord();
    void onresumerecord();
    void onstoprecord(string stoptip);
    void onrecording(string timetip);
  }
  public interface onpagerecordlistener {
    void onstartrecord();
    void onstoprecord();
    void onbeforeshowanim();
    void onafterhideanim();
  }
}

到了最后了,是一些调用时的内容

public class mainactivity extends appcompatactivity {
  private static final string tag = mainactivity.class.getsimplename();
  private button mbtn;
  private final int request_allow = 100;
  private button mbutton;
  //bindservice需要创建连接
  private serviceconnection mconnection = new serviceconnection() {
    @override
    public void onserviceconnected(componentname name, ibinder service) {
      //启动service
      talscreenrecordservice.recordbinder recordbinder = (talscreenrecordservice.recordbinder) service;
      talscreenrecordservice recordservice = recordbinder.getrecordservice();
      //这个其实是传值在使用的activity中拿到service
      talscreenutils.setscreenservice(recordservice);
    }
    @override
    public void onservicedisconnected(componentname name) {
    }
  };
 //开启service,意图跳转到service,别忘了androidmanifest里面需要注册这个service哦
  private void startservice() {
    intent intent = new intent(mainactivity.this, talscreenrecordservice.class);
    bindservice(intent, mconnection, bind_auto_create);
  }
  @override
  protected void oncreate(final bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    mbtn = findviewbyid(r.id.btn);
    mbutton = findviewbyid(r.id.button2);
    initview();
    //两个按钮 一个开始 一个结束 xml不贴了
    mbtn.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        if (talfileutils.getfreemem(mainactivity.this) < 100) {
          toast.maketext(mainactivity.this, "手机内存不足,请清理后再进行录屏", toast.length_short).show();
          return;
        }
        //开始录屏录音
        talscreenutils.startscreenrecord(mainactivity.this, request_allow);
      }
    });
    mbutton.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        stop();
        log.i(tag, "onclick: " + stop());
      }
  //停止录屏录音返回路径
      private string stop() {
        talscreenutils.stopscreenrecord(mainactivity.this);//停止
        return talscreenutils.getscreenrecordfilepath();
      }
    });
  }
  @override
  protected void onstart() {
    super.onstart();

  }

  private void initview() {
    //权限申请
    talallow.requestpermissions(this, request_allow);
    //获取屏幕大小 在oncreate里面初始化就可以获取
    talscreenparams.init(this);
    startservice();
  }

  @override
  protected void onstop() {
    super.onstop();
    //在对用户可见不可交互的时候防止异常
    talscreenutils.clear();
  }
 //打印权限获取情况日志
  @override
  public void onrequestpermissionsresult(int requestcode, @nonnull string[] permissions, @nonnull int[] grantresults) {
    toast.maketext(this, permissions[0] + "\n" + grantresults[0], toast.length_short).show();
    super.onrequestpermissionsresult(requestcode, permissions, grantresults);
  }
 //在用户允许录屏后拿到确定的code 跟data
  @override
  protected void onactivityresult(int requestcode, int resultcode, @nullable intent data) {
    super.onactivityresult(requestcode, resultcode, data);
    if (requestcode == request_allow && data != null) {
      try {
      //设置数据,在用户允许后 调用了开始录屏的方法
        talscreenutils.setupdata(resultcode, data);
        //拿到路径
        string screenrecordfilepath = talscreenutils.getscreenrecordfilepath();
        if (screenrecordfilepath == null) {
          toast.maketext(this, "空的", toast.length_short).show();
        }
        toast.maketext(mainactivity.this, "" + screenrecordfilepath, toast.length_short).show();
        log.i("zlq", "onclick: " + screenrecordfilepath);
      } catch (exception e) {
        e.printstacktrace();
      }
    } else {
      toast.maketext(this, "禁止录屏", toast.length_short).show();
    }
  }

  @override
  protected void ondestroy() {
    super.ondestroy();
    unbindservice(mconnection);
  }
}

至此,一个还算比较完整的录屏录音功能就可以实现,不足之处请批评指正

总结

到此这篇关于android mediarecorder录屏时带录音功能实现的文章就介绍到这了,更多相关android mediarecorder录屏带录音内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!