屏幕录制调查整理

需求:
        
调查制作一个简单的桌面屏幕录制的小工具。

环境:
        
windows。

语言:
        
c#,java。

工具:
        Visual Studio 2017,SpringToolSuite4.exe。

方案:
        1.AForge.dll+AForge.Video.dll+AForge.Video.FFMPEG.dll
        2.Oraycn.Mcapture.dll+Oraycn.Mfile.dll
        3.SharpDX.dll+SharpDX.DXGI.dll+SharpDX.Direct3D11.dll
        4.ffmpeg.exe+javajre+screen-capture-recorder
        5.ffmpeg.exe
        6.javacv

代码:
        1.AForge.dll+AForge.Video.dll+AForge.Video.FFMPEG.dll(开源免费)

        项目准备:

                a.下载AForge.Video.FFMPEG.dll
                        http://www.aforgenet.com/framework/downloads.html
                                        
                b.创建C# win form项目

                c.导入AForge.dll+AForge.Video.dll+AForge.Video.FFMPEG.dll
                    

         核心代码:(转载自c#屏幕录制 - yyq745201 - 博客园

using AForge.Video;
using AForge.Video.FFMPEG;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    class ScreenRecorderTool
    {
        #region Fields
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// 比特率
        /// 比特率是指每单位时间(比特)发送的比特数。
        /// </summary>
        public enum BitRate : int
        {
            _1000kbit = 1000000,
            _2000kbit = 2000000,
            _3000kbit = 3000000,
            _4000kbit = 4000000,
            _5000kbit = 5000000,
            _6000kbit = 6000000,
            _7000kbit = 7000000,
            _8000kbit = 8000000
        }

        //屏幕宽度
        private int screenWidth;
        //屏幕高度
        private int screenHight;
        //画面的比特率
        private int bitRate = (int)BitRate._5000kbit;
        //画面的帧率,默认为5
        private int frameRate = 20;

        //是否在录屏
        static bool isRecording;
        //lock 
        private static object key = new object();
        //视频文件名 默认为video-yyy-MM-dd-HH-mm-ss-ff.avi
        private string fileName;
        //视频文件保存路径
        private string saveFolderPath;
        //桌面画面
        private Rectangle screenArea;
        //用于使用FFmpeg库写入视频文件的类。
        private VideoFileWriter videoWriter;
        //屏幕抓取视频源。
        private ScreenCaptureStream videoStreamer;
        //从FFmpeg库中列举了一些视频编解码器
        private VideoCodec videoCodec = VideoCodec.MSMPEG4v2;
        //截图间隔毫秒。
        private int frameInterval = 50;
        //计时器
        private Stopwatch stopWatch;

        

        /// <summary>
        /// 是否在录屏
        /// </summary>
        private bool IsRecording
        {
            get
            {
                lock (key)
                {
                    return isRecording;
                }
            }
            set
            {
                lock (key)
                {
                    isRecording = value;
                }
            }
        }
        #endregion

        /// <summary>
        /// 初期设置
        /// </summary>
        public ScreenRecorderTool()
        {
            IsRecording = false;
            this.stopWatch = new Stopwatch();
            this.screenArea = Rectangle.Empty;
            this.SetScreenArea();
            this.screenWidth = SystemInformation.VirtualScreen.Width;
            this.screenHight = SystemInformation.VirtualScreen.Height;
            this.saveFolderPath = AppDomain.CurrentDomain.BaseDirectory;
        }

        /// <summary>
        /// 将画面的记录区域设定为全屏
        /// </summary>
        private void SetScreenArea()
        {
            foreach (Screen screen in Screen.AllScreens)
            {
                this.screenArea = Rectangle.Union(this.screenArea, screen.Bounds);
            }

            if (this.screenArea == Rectangle.Empty)
            {
                logger.Error("未获取画面信息");
                throw new InvalidOperationException("未获取画面信息");
            }
        }

        /// <summary>
        /// 设置打开视频写入工具所需的参数
        /// </summary>
        private void InitializeRecordingParameters()
        {
            if (!IsRecording)
            {
                IsRecording = true;
                //创建目录
                this.CreateVideoFolder();
                //设定视频文件名
                if (string.IsNullOrEmpty(this.fileName))
                {
                    this.fileName = string.Format
                       (@"{0}-{1}.avi",
                       "video",
                       DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff"));
                }
               
                string filePath = saveFolderPath + fileName;
                //以指定的名称和属性创建视频文件。
                this.videoWriter.Open(filePath, this.screenWidth, this.screenHight, this.frameRate, this.videoCodec, this.bitRate);
            }
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        private void CreateVideoFolder()
        {
            if (saveFolderPath == AppDomain.CurrentDomain.BaseDirectory)
            {
                string folderPath = saveFolderPath + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                if (!System.IO.Directory.Exists(folderPath))
                {
                    System.IO.Directory.CreateDirectory(folderPath);
                }
                this.saveFolderPath = folderPath;
            }
        }

        /// <summary>
        /// 完成录屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VideoWriterNewFrame(object sender, NewFrameEventArgs e)
        {
            if (IsRecording)
            {
                if (videoWriter != null)
                {
                    this.videoWriter.WriteVideoFrame(e.Frame);
                }
            }
            else
            {
                //结束录像,创建视频文件
                this.StopRecording();
                this.videoStreamer.SignalToStop();
                this.videoWriter.Close();
                this.videoWriter.Dispose();
                GC.Collect();
            }
        }

        #region public method
        /// <summary>
        /// 设置计时器
        /// </summary>
        public Stopwatch StopWatch
        {
            get { return this.stopWatch; }
            set
            {
                if (value != null)
                {
                    throw new ArgumentNullException("stopWatch", "计时器不能为空");
                }
                this.stopWatch = value;
            }
        }

        /// <summary>
        /// 设置视频保存位置
        /// </summary>
        public string SaveFolderPath
        {
            get { return this.saveFolderPath; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("saveFolderpath", "保存位置不能为空");
                }
                this.saveFolderPath = value;
            }
        }

        /// <summary>
        /// 设定视频文件名
        /// </summary>
        public string FileName
        {
            get { return this.fileName; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("fileName", "文件名不能为空");
                }
                this.fileName = value;
            }
        }

        /// <summary>
        /// 打开视频流,开始录像
        /// </summary>
        public void StartRecording()
        {
            this.videoWriter = new VideoFileWriter();
            this.InitializeRecordingParameters();
            this.videoStreamer = new ScreenCaptureStream(this.screenArea);
            this.videoStreamer.NewFrame += new NewFrameEventHandler(VideoWriterNewFrame);
            //截图间隔毫秒。
            this.videoStreamer.FrameInterval = this.frameInterval;
            //开始录屏
            this.videoStreamer.Start();
            //开始计时
            this.stopWatch.Start();
            IsRecording = true;
            Console.WriteLine("开始录屏了");
        }

        /// <summary>
        /// 结束录屏
        /// </summary>
        public void StopRecording()
        {
            IsRecording = false;
            this.stopWatch.Stop();

            Console.WriteLine("结束录屏了");

        }
        #endregion

    }

}

        调用代码:

ScreenRecorderTool screenRecorderTool = new ScreenRecorderTool();
//开始
screenRecorderTool.StartRecording();
//结束
screenRecorderTool.StopRecording();

        2.Oraycn.Mcapture.dll+Oraycn.Mfile.dll(部分开源免费)

        项目准备:
                可以在这个网址上下载到具体的使用demo:Oraycn.RecordDemo.rar,使用C#实现的。可以用VS2017直接打开,然后体验他们做的工具,此demo程序只能录制5分钟视频。
               

         3.SharpDX.dll+SharpDX.DXGI.dll+SharpDX.Direct3D11.dll

                Home | SharpDX
                UWP项目,后续更新

         4.ffmpeg.exe+javajre+screen-capture-recorder(开源免费)

                项目准备:

                        需要安装screen-capture-recorder
                        需要Java的运用环境
                        需要下载Ffmpeg.exe

                执行命令:

                        cmd进入ffmpeg.exe的路径,

ffmpeg -rtbufsize 100M -f dshow -i   video="screen-capture-recorder":audio="virtual-audio-capturer" -vcodec libx264  -preset veryfast -crf 22 -tune:v zerolatency  -pix_fmt yuv420p  -s  1280x720  -acodec libmp3lame filename.flv

 做成的视频filename.flv,在ffmpeg.exe的路径,如果不能播放,下载VLC media player后,尝试播放。

                C#代码

                        参考5.ffmpeg.exe(开源免费)的C#代码

         5.ffmpeg.exe(开源免费)

                项目准备:

                         需要下载Ffmpeg.exe

                执行命令:

                        cmd进入ffmpeg.exe的路径,做成out.mp4,可以通过微软自带的播放器打开。

ffmpeg -f gdigrab -framerate 25 -i desktop -s 1920*1080 -pix_fmt yuv420p -c:v h264 -b:v 2000k .\out.mp4

         C#代码:(转载自:基于FFMpeg的C#录屏全攻略 - DHUtoBUAA - 博客园

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ScreenRecord
{
    public partial class ScreenRecordTools : Form
    {
       
        #region Fields
        //屏幕的宽度
        private int screenWidth;
        //屏幕的高度
        private int screenHight;
        //视频文件名 默认为video-yyyy-MM-dd-HH-mm-ss-ff.avi 
        private string fileName;
        //保存路径
        private string saveFolderPath;
        //计时器
        private Stopwatch stopWatch;
        //建立外部调用线程 
        private Process proc;

        #endregion

        #region 初期设置
        ///<summary> 
        ///返回 .exe.config 文件的 appSettings 配置部分中的值字段 
        ///</summary> 
        ///<param name="strKey"></param> 
        ///<returns></returns> 
        private string GetAppConfig(string strKey)
        {
            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.TrimEnd('\\') + "\\ScreenRecord.config";
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }
        /// <summary>
        /// 初期设置
        /// </summary>
        public ScreenRecordTools()
        {
            this.InitializeComponent();
            this.stopWatch = new Stopwatch();
            this.screenWidth = SystemInformation.VirtualScreen.Width;
            this.screenHight = SystemInformation.VirtualScreen.Height;
            string videoName = GetAppConfig("fileName");
            string videoPath = GetAppConfig("saveFolderPath");

            if (!string.IsNullOrEmpty(videoName))
            {
                this.fileName = videoName;
            }

            if (!string.IsNullOrEmpty(videoPath))
            {
                this.saveFolderPath = videoPath;
            }
            else
            {
                this.saveFolderPath = AppDomain.CurrentDomain.BaseDirectory;
            }
        }
        #endregion

        #region 录屏操作
        /// <summary>
        /// 创建目录
        /// </summary>
        private void CreateVideoFolder()
        {
            string folderPath = saveFolderPath + "\\";
            if (!System.IO.Directory.Exists(folderPath))
            {
                System.IO.Directory.CreateDirectory(folderPath);
            }
            this.saveFolderPath = folderPath;
        }


        /// <summary>
        /// 开始录屏
        /// </summary>
        /// <param name="outFilePath">输出视频保存路径</param>
        private void RunFFmpeg(string outFilePath)
        {
            Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
            Debug.WriteLine(KillProcessArray.Length.ToString());
            foreach (Process KillProcess in KillProcessArray)
            {
                KillProcess.Kill();
            }

            string ffmpegPath = AppDomain.CurrentDomain.BaseDirectory + @"bin\ffmpeg.exe";
            //ffmpeg的参数
            //@"-f dshow -i video=""screen-capture-recorder"" -r 15 -vcodec libx264 -preset:v ultrafast -tune:v zerolatency D:\MyDesktop.mkv";
            string arguments = @"-f gdigrab -framerate 25 -i desktop -s "+ this.screenWidth+ "*" + this.screenHight + " -pix_fmt yuv420p -c:v h264 -b:v 2000k " + outFilePath;

            ProcessStartInfo oInfo = new ProcessStartInfo(ffmpegPath, arguments);
            //是否开始使用操作系统shell 
            oInfo.UseShellExecute = false;
            //不显示程序窗口 
            oInfo.CreateNoWindow = true;
            //重定向标准错误 
            oInfo.RedirectStandardOutput = true;
            oInfo.RedirectStandardError = true;
            oInfo.RedirectStandardInput = true;

            //开始录屏
            this.proc = Process.Start(oInfo);
            //开始计时
            this.stopWatch.Start();
            this.proc.EnableRaisingEvents = true;
            this.proc.BeginErrorReadLine();
            Console.WriteLine("录屏开始了");

            
        }

        #endregion

        #region public
        /// <summary>
        /// 设置计时器
        /// </summary>
        public Stopwatch StopWatch
        {
            get { return this.stopWatch; }
            set
            {
                if (value != null)
                {
                    throw new ArgumentNullException("stopWatch", "计时器不能为空");
                }
                this.stopWatch = value;
            }
        }
        
        /// <summary>
        /// 设置保存路径
        /// </summary>
        public string SaveFolderPath
        {
            get { return this.saveFolderPath; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("saveFolderpath", "保存路径不能为空");
                }
                this.saveFolderPath = value;
            }
        }

        /// <summary>
        /// 设置视频文件名
        /// </summary>
        public string FileName
        {
            get { return this.fileName; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("fileName", "文件名不能为空");
                }
                this.fileName = value;
            }
        }

        /// <summary>
        /// 设置打开视频刻录工具所需的参数
        /// </summary>
        public void StartScreenRecord()
        {
            //创建目录
            this.CreateVideoFolder();
            //设置视频文件名 
            if (string.IsNullOrEmpty(this.fileName))
            {
                this.fileName = string.Format
                    (@"{0}-{1}.avi",
                    "video",
                    DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff"));
            }

            string filePath = saveFolderPath + fileName;
            //创建具有指定名称和属性的视频文件。
            RunFFmpeg(filePath);
        }

        /// <summary>
        /// 结束录屏
        /// </summary>
        public void StopScreenRecord()
        {
            this.proc.StandardInput.WriteLine("q");
            this.proc.StandardInput.AutoFlush = true;
            this.proc.WaitForExit();
            this.proc.Close();
            this.proc.Dispose();
            Console.WriteLine("结束录屏了");
        }
        #endregion
    }
}

        ScreenRecord.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!-- 文件保存路径  -->
    <!-- 文件保存路径  默认:现在的路径 -->
    <!-- 文件保存路径  例如:E:\\ -->
    <add key="saveFolderPath" value=""></add>
    <!-- 文件名-->
    <!-- 文件名 默认:video-yyyy-MM-dd-HH-mm-ss-ff.avi-->
    <!-- 文件名 例如:test.avi-->
    <add key="fileName" value=""></add>
  </appSettings>
</configuration>

         6.javacv(开源免费)

                项目准备:

                        使用SpringToolSuite4.exe创建一个gradle项目,在build.gradle中添加一行代码,刷新gradle项目,等待下载javacv相关的jia包。

implementation group: 'org.bytedeco', name: 'javacv-platform', version: '1.5.6'

                        下载完成后,在其中找到如下6个jar包
                          

                        然后创建一个简单的java工程将上面几个引入。
                核心代码:(转载自:java 实现简单录屏功能 - 见怪见外 - 博客园)

package desktopRecord;

import java.awt.AWTException;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Scanner;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

//import org.bytedeco.javacpp.avcodec;
//import org.bytedeco.javacpp.avutil;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
//import org.bytedeco.javacv.FrameRecorder.Exception;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
/**
 * 使用javacv进行录屏
 * 
 */
public class VideoRecord {
	//线程池 screenTimer
    private ScheduledThreadPoolExecutor screenTimer;
    //获取屏幕尺寸
    private final Rectangle rectangle = new Rectangle(Constant.WIDTH, Constant.HEIGHT); // 截屏的大小
    //视频类 FFmpegFrameRecorder
    private FFmpegFrameRecorder recorder;
    private Robot robot;
    //线程池 exec
    private ScheduledThreadPoolExecutor exec;
    private TargetDataLine line;
    private AudioFormat audioFormat;
    private DataLine.Info dataLineInfo;
    private boolean isHaveDevice = true;
    private long startTime = 0;
    private long videoTS = 0;
    private long pauseTime = 0;
    private double frameRate = 5;

    public VideoRecord(String fileName, boolean isHaveDevice) {
        recorder = new FFmpegFrameRecorder(fileName + ".mp4", Constant.WIDTH, Constant.HEIGHT);
        // recorder.setVideoCodec(avcodec.AV_CODEC_ID_H265); // 28
        // recorder.setVideoCodec(avcodec.AV_CODEC_ID_FLV1); // 28
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_MPEG4); // 13 //
        recorder.setFormat("mp4");
        // recorder.setFormat("mov,mp4,m4a,3gp,3g2,mj2,h264,ogg,MPEG4");
        recorder.setSampleRate(44100);
        recorder.setFrameRate(frameRate);

        recorder.setVideoQuality(0);
        recorder.setVideoOption("crf", "23");
        // 2000 kb/s, 720P视频的合理比特率范围
        recorder.setVideoBitrate(1000000);
        /**
         * 权衡quality(视频质量)和encode speed(编码速度) values(值): ultrafast(终极快),superfast(超级快),
         * veryfast(非常快), faster(很快), fast(快), medium(中等), slow(慢), slower(很慢),
         * veryslow(非常慢)
         * ultrafast(终极快)提供最少的压缩(低编码器CPU)和最大的视频流大小;而veryslow(非常慢)提供最佳的压缩(高编码器CPU)的同时降低视频流的大小
         * 参考:https://trac.ffmpeg.org/wiki/Encode/H.264 官方原文参考:-preset ultrafast as the
         * name implies provides for the fastest possible encoding. If some tradeoff
         * between quality and encode speed, go for the speed. This might be needed if
         * you are going to be transcoding multiple streams on one machine.
         */
        recorder.setVideoOption("preset", "ultrafast");
        recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P); // yuv420p
        recorder.setAudioChannels(2);
        recorder.setAudioOption("crf", "0");
        // Highest quality
        recorder.setAudioQuality(0);
        recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC); //

        try {
        	robot = new Robot();
            recorder.start();
        } catch (AWTException awte) {
        	awte.printStackTrace();
        } catch (Exception e) {
            System.out.print("*******************************");
            e.printStackTrace();
        }
        this.isHaveDevice = isHaveDevice;
    }

    /**
     * 开始录制
     */
    public void start() {

        if (startTime == 0) {
            startTime = System.currentTimeMillis();
        }
        if (pauseTime == 0) {
            pauseTime = System.currentTimeMillis();
        }
        // 如果有录音设备则启动录音线程
        if (isHaveDevice) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    caputre();
                }
            }).start();

        }

        // 录屏
        screenTimer = new ScheduledThreadPoolExecutor(1);
        screenTimer.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

                // 将screenshot对象写入图像文件
                // try {
                // ImageIO.write(screenCapture, "JPEG", f);
                // videoGraphics.drawImage(screenCapture, 0, 0, null);
                // IplImage image = cvLoadImage(name); // 非常吃内存!!
                // // 创建一个 timestamp用来写入帧中
                // videoTS = 1000
                // * (System.currentTimeMillis() - startTime - (System.currentTimeMillis() -
                // pauseTime));
                // // 检查偏移量
                // if (videoTS > recorder.getTimestamp()) {
                // recorder.setTimestamp(videoTS);
                // }
                BufferedImage screenCapture = robot.createScreenCapture(rectangle); // 截屏
                
                BufferedImage videoImg = new BufferedImage(Constant.WIDTH, Constant.HEIGHT,
                        BufferedImage.TYPE_3BYTE_BGR); // 声明一个BufferedImage用重绘截图
                
                Graphics2D videoGraphics = videoImg.createGraphics();// 创建videoImg的Graphics2D
                
                videoGraphics.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
                videoGraphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
                        RenderingHints.VALUE_COLOR_RENDER_SPEED);
                videoGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
                videoGraphics.drawImage(screenCapture, 0, 0, null); // 重绘截图
                
                Java2DFrameConverter java2dConverter = new Java2DFrameConverter();
                
                Frame frame = java2dConverter.convert(videoImg);
                try {
                    videoTS = 1000L
                            * (System.currentTimeMillis() - startTime - (System.currentTimeMillis() - pauseTime));
                    // 检查偏移量
                    if (videoTS > recorder.getTimestamp()) {
                        recorder.setTimestamp(videoTS);
                    }
                    recorder.setAudioChannels(1);
                    recorder.record(frame); // 录制视频
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 释放资源
                videoGraphics.dispose();
                videoGraphics = null;
                videoImg.flush();
                videoImg = null;
                java2dConverter.close();
                java2dConverter = null;
                screenCapture.flush();
                screenCapture = null;

            }
        }, (int) (1000 / frameRate), (int) (1000 / frameRate), TimeUnit.MILLISECONDS);

    }

    /**
     * 抓取声音
     */
    public void caputre() {
        audioFormat = new AudioFormat(44100.0F, 16, 2, true, false);
        dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
        
        try {
        	line = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
            line.open(audioFormat);
            line.start();
        } catch (LineUnavailableException e1) {
            System.out.println("#################");
            e1.printStackTrace();
        }
        

        final int sampleRate = (int) audioFormat.getSampleRate();
        final int numChannels = audioFormat.getChannels();

        int audioBufferSize = sampleRate * numChannels;
        final byte[] audioBytes = new byte[audioBufferSize];

        exec = new ScheduledThreadPoolExecutor(1);
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    int nBytesRead = line.read(audioBytes, 0, line.available());
                    int nSamplesRead = nBytesRead / 2;
                    short[] samples = new short[nSamplesRead];

                    // Let's wrap our short[] into a ShortBuffer and
                    // pass it to recordSamples
                    ByteBuffer.wrap(audioBytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(samples);
                    ShortBuffer sBuff = ShortBuffer.wrap(samples, 0, nSamplesRead);

                    // recorder is instance of
                    // org.bytedeco.javacv.FFmpegFrameRecorder
                    recorder.recordSamples(sampleRate, numChannels, sBuff);
                    // System.gc();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, (int) (1000 / frameRate), (int) (1000 / frameRate), TimeUnit.MILLISECONDS);
    }

    /**
     * 停止
     */
    public void stop() {
        if (null != screenTimer) {
            screenTimer.shutdownNow();
            while(!screenTimer.isTerminated());
        }
        try {
            recorder.stop();
            recorder.release();
            recorder.close();
            screenTimer = null;
            // screenCapture = null;
            if (isHaveDevice) {
                if (null != exec) {
                    exec.shutdownNow();
                }
                if (null != line) {
                    line.stop();
                    line.close();
                }
                dataLineInfo = null;
                audioFormat = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 暂停
     * 
     * @throws Exception
     */
    public void pause() throws Exception {
        screenTimer.shutdownNow();
        screenTimer = null;
        if (isHaveDevice) {
            exec.shutdownNow();
            exec = null;
            line.stop();
            line.close();
            dataLineInfo = null;
            audioFormat = null;
            line = null;
        }
        pauseTime = System.currentTimeMillis();
    }

    
    
    public static void main(String[] args) throws Exception, AWTException {
    	boolean isStop = true;
        VideoRecord videoRecord = new VideoRecord("D:\\test", false);
        videoRecord.start();
        System.out.println("やめたいですか? 入力(stop)するとプログラムが停止します。");
        while (isStop) {
            Scanner sc = new Scanner(System.in);
            if (sc.next().equalsIgnoreCase("stop")) {
            	sc.close();
            	isStop = false;
                videoRecord.stop();
                System.out.println("停止");
            }            
        }
    }
}

class Constant{
    public final static int WIDTH=Toolkit.getDefaultToolkit().getScreenSize().width;
    public final static int HEIGHT=Toolkit.getDefaultToolkit().getScreenSize().height;

}

总结:

        各种录屏,各种坑,相比较,自用建议优先选择顺为:5→1→4→6→2→3。商用自行考虑。

         

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值