Screen Recording (Video) of Java Webdriver script

Sauce lab provided screen capturing functionality to test scripts execution, I was looking same type functionality to work on local machine and came up across “Monte Media Library” java based library developed by Werner Randelshofer.. In this post I have described a way to capture screen cast/ Video recording of selenium/webdriver test script execution.

Step to implement Monte Media library to selenium/Webdriver test scripts.
  1. Download “MonteScreenRecorder.jar” from link http://www.randelshofer.ch/monte/
  2. Add this jar file to your selenium/webdriver eclipse project.
  3. This jar file contain “ScreenRecorder” class, we need to create this class object by following way.

GraphicsConfiguration gc = GraphicsEnvironment
      .getLocalGraphicsEnvironment()
      .getDefaultScreenDevice()
      .getDefaultConfiguration();


ScreenRecorder  screenRecorder = new ScreenRecorder(gc,
      new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
      new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
              CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
              DepthKey, 24, FrameRateKey, Rational.valueOf(15),
              QualityKey, 1.0f, KeyFrameIntervalKey, 15 * 60),
              new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black",
              FrameRateKey, Rational.valueOf(30)),null);

   4. Need to call “screenRecorder.start()” methods at starting of your test scripts and "screenRecorder.stop()” at the end of execution.
   5. Below is complete test script example

package com.TestScripts;

import java.awt.*;
import java.io.File; 
import org.monte.media.Format;
import org.monte.media.math.Rational;
import org.monte.screenrecorder.ScreenRecorder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.monte.media.AudioFormatKeys.*;
import static org.monte.media.VideoFormatKeys.*;
 
public class VideoReord {
    private ScreenRecorder screenRecorder;
   
     public static void main(String[] args) throws Exception {
                                                                  
          VideoReord  videoReord = new VideoReord();
          videoReord.startRecording();                                         
                        
          WebDriver driver = new FirefoxDriver();                                      
          driver.get("http://www.google.com");
                          
          WebElement element = driver.findElement(By.name("q"));                                       
          element.sendKeys("testing");                                      
          element.submit();                   
          System.out.println("Page title is: " +driver.getTitle());                                                                        
          driver.quit();                                
          videoReord.stopRecording();
    }
   

       public void startRecording() throws Exception
       {
                            
            GraphicsConfiguration gc = GraphicsEnvironment
               .getLocalGraphicsEnvironment()
               .getDefaultScreenDevice()
               .getDefaultConfiguration();

           this.screenRecorder = new ScreenRecorder(gc,
               new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
               new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                    CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                    DepthKey, 24, FrameRateKey, Rational.valueOf(15),
                    QualityKey, 1.0f,
                    KeyFrameIntervalKey, 15 * 60),
               new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black",
                    FrameRateKey, Rational.valueOf(30)),
               null);
          this.screenRecorder.start();
        
       }

       public void stopRecording() throws Exception
       {
         this.screenRecorder.stop();
       }
}


   6. After execution test script, video file is generated under “Video” folder of current user folder in   Windows machine and “Movies” folder on Mac machine.

I am getting some comments for saving video in a desire location, I am going to update my post as Michael’s suggestion. Thanks again for his help.
If you need to save video file in desire location, then you need to override “createMovieFile” function of “ScreenRecorder” class class for creating a new folder and file. For this you need to create another class like “SpecializedScreenRecorder” and extend “ScreenRecorder” class as below:
package com.test;

import java.awt.AWTException;
import java.awt.GraphicsConfiguration;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.monte.media.Format;
import org.monte.media.Registry;
import org.monte.screenrecorder.ScreenRecorder;

public class SpecializedScreenRecorder extends ScreenRecorder {

    private String name;

    public SpecializedScreenRecorder(GraphicsConfiguration cfg,
           Rectangle captureArea, Format fileFormat, Format screenFormat,
           Format mouseFormat, Format audioFormat, File movieFolder,
           String name) throws IOException, AWTException {
         super(cfg, captureArea, fileFormat, screenFormat, mouseFormat,
                  audioFormat, movieFolder);
         this.name = name;
    }

    @Override
    protected File createMovieFile(Format fileFormat) throws IOException {
          if (!movieFolder.exists()) {
                movieFolder.mkdirs();
          } else if (!movieFolder.isDirectory()) {
                throw new IOException("\"" + movieFolder + "\" is not a directory.");
          }
                          
          SimpleDateFormat dateFormat = new SimpleDateFormat(
                   "yyyy-MM-dd HH.mm.ss");
                        
          return new File(movieFolder, name + "-" + dateFormat.format(new Date()) + "."
                  + Registry.getInstance().getExtension(fileFormat));
    }
 }

Now you need to create object of  “SpecializedScreenRecorder” instead of creating “Screen” class object.
package com.test;

import java.awt.*;
import java.io.File;
import org.monte.media.Format;
import org.monte.media.math.Rational;
import org.monte.screenrecorder.ScreenRecorder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.monte.media.AudioFormatKeys.*;
import static org.monte.media.VideoFormatKeys.*;

public class VideoReord {
    private ScreenRecorder screenRecorder;
 
     public static void main(String[] args) throws Exception {
                                                                
             VideoReord  videoReord = new VideoReord();
             videoReord.startRecording();                                       
                      
             WebDriver driver = new FirefoxDriver();                                    
             driver.get("http://www.google.com");
                         
             WebElement element = driver.findElement(By.name("q"));                                     
             element.sendKeys("testing");                                    
             element.submit();                   
             System.out.println("Page title is: " + driver.getTitle());                                                                       
             driver.quit();                              
             videoReord.stopRecording();
       }
 

       public void startRecording() throws Exception
       {    
              File file = new File("D:\\Videos");
                           
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              int width = screenSize.width;
              int height = screenSize.height;
                            
              Rectangle captureSize = new Rectangle(0,0, width, height);
                            
            GraphicsConfiguration gc = GraphicsEnvironment
               .getLocalGraphicsEnvironment()
               .getDefaultScreenDevice()
               .getDefaultConfiguration();

           this.screenRecorder = new SpecializedScreenRecorder(gc, captureSize,
               new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
               new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                    CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                    DepthKey, 24, FrameRateKey, Rational.valueOf(15),
                    QualityKey, 1.0f,
                    KeyFrameIntervalKey, 15 * 60),
               new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black",
                    FrameRateKey, Rational.valueOf(30)),
               null, file, "MyVideo");
          this.screenRecorder.start();
      
       }

       public void stopRecording() throws Exception
       {
         this.screenRecorder.stop();
       }
}

Above code explanation: Create a File class object and pass path where you want to save your video
   File file = new File("D:\\Videos");
Create dimension of your screen to capture video, I have created object for default screen.
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   int width = screenSize.width;
   int height = screenSize.height;
                            
    Rectangle captureSize = new Rectangle(0,0, width, height);
Now Create object of “SpecializedScreenRecorder” and pass Rectangle object, File object, and file name as a last argument and rest are same.
Run your test, you will see that a video will generate under your desire location.

101 comments:

  1. Hi,

    I just ran the above sample test... but I'm unable to locate the recorded video file in Windows XP machine... Could you please help me in locating the recorded video...

    I have checked the below location after test execution but not found any file under it.

    \My Documents\My Videos

    ReplyDelete
  2. I got it where to check.. Can you please tell me how to set the name of the recording video...? for example, I want to set to test name+DateTimeFormat...

    ReplyDelete
    Replies
    1. String ext = "dat";
      File dir = new File("/home/pregzt");
      String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
      File file = new File(dir, name);

      Delete
  3. Hi Bharath,

    I am working on same and will update in post If I get any solution for this.

    ReplyDelete
  4. public class SpecializedScreenRecorder extends ScreenRecorder {

    private string name;

    public SpecializedScreenRecorder(GraphicsConfiguration cfg, Rectangle captureArea, Format fileFormat, Format screenFormat,
    Format mouseFormat, Format audioFormat, File movieFolder, String Name) throws IOException, AWTException {
    super(cfg, captureArea, fileFormat, screenFormat, mouseFormat, audioFormat, movieFolder);
    this.name = name;
    }

    @Override
    protected File createMovieFile(Format fileFormat) throws IOException {
    if (!movieFolder.exists()) {
    movieFolder.mkdirs();
    } else if (!movieFolder.isDirectory()) {
    throw new IOException("\"" + movieFolder + "\" is not a directory.");
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddTHH.mm.ss");
    Date date = new Date();
    return new File(movieFolder, name + "-" + dateFormat(new Date()) + "." + Registry.getInstance().getExtension(fileFormat));
    }
    }

    ReplyDelete
    Replies
    1. Thanks a lot Michael for providing this solution.

      Delete
    2. Thanks for the solution. This is working perfectly.I am getting screen recording files with my own custom name.

      Delete
  5. here is one more post of screen recording in webdriver and C#

    http://roadtoautomation.blogspot.in/2013/07/road-to-screen-recording-in-webdriver.html#more

    ReplyDelete
  6. Thanks, very good post for video recording in webdriver..

    ReplyDelete
  7. My video file is not playing . Its size is 277Mb.

    ReplyDelete
  8. How to change the video saving location as now it saves under My Videos by default ?

    ReplyDelete
    Replies
    1. did you tried above Michael comment ?

      Delete
    2. I'm not sure how to use that code ? Can you please post an example .

      Would be really help full

      Delete
  9. When my test on jenkins the path for the video is as below by default
    [C:\Windows\System32\config\systemprofile\Videos\ScreenRecording 2013-10-03 at 15.12.18.avi]

    but in this location i dont find any Videos folder.
    Can you please help me on this

    ReplyDelete
  10. need maven depedency..how to add it to maven repository

    ReplyDelete
    Replies
    1. You download jar file and install in maven repository just running like below command

      mvn install:install-file -DgroupId=org.monte -DartifactId=MonteScreenRecorder -Dversion={versionName} -Dpackaging=jar -Dfile={YourPath}/MonteScreenRecorder.jar

      Now you can add maven dependency in your pom.xml accordingly.

      Delete
  11. When tests are running, if the machine is disconnected, it records black.

    ReplyDelete
    Replies
    1. What do you means machine is disconnected ?

      Delete
    2. The remote mechine not in user control

      Delete
    3. The remote mechine is not in the control of user

      Delete
  12. Can you please help me on my issue

    ReplyDelete
    Replies
    1. Hi Sai, I have update code for saving video in desire location. look into it Hope this will help you.

      Delete
  13. Hi, Is there any way so that we can save the video under project folder or any other desired location?
    I tried Michael's code but it was bit complex for me. Could you please give an example for the same.

    ReplyDelete
    Replies
    1. Hi Neelam, I have update code for saving video in desire location. look into it

      Delete
    2. Thanks alot for your help. I need one more help i.e. i need to take screenshots of every page which i have already created but i need to put screenshots in different folders for every time. For example i am giving online test for 200 students and each student has to cover 30 pages during test(I have to take screenshots of all 30pages and put in a folder like Student1). So after completion of test for one student i need to cover all 200 students and need to make screenshot folders for all.

      Delete
    3. Create a function for creating dynamic folder and call function at starting of your test so by this way you can get a dynamic folder in each execution.

      Now capture screenshot of each steps and put into created folder.

      In this way you can create a new folder in each execution and have a screen shot.

      Delete
    4. Works for me :) . Thanks alot again for giving me such a helpful logic.

      Delete
  14. Thanks for updating post....
    Now i am able save video

    ReplyDelete
  15. I cannot open the recorded file and getting "Windows Media Player cannot play the file. The file may be formatted with an unsupported codec, or the Internet security setting on your computer is set too high. Lower your browser's security setting, and then try again"

    ReplyDelete
  16. Thanks for the post... Great work... Is it possible to record script while running in remote machine.?

    ReplyDelete
  17. Hi Admin,
    My video script was working perfectly and i was able to save and play the recorded video. I have deployed my script on Virtual Machine and my clients used to run it through UI(which I have provided them) but i am facing new problem as only black screen appearing when i play the video. I mean video get saved successfully but when i play them, only black screen is appearing. Though video is playing perfectly when run the script locally on my system(when video save on my system). Please help me

    ReplyDelete
    Replies
    1. Hi did you solved this problem???

      Delete
    2. Hi, I'm having the same issue.. Did you manage to solve it? Thanks

      Delete
    3. No if you got any solution please let me know !!

      Delete
    4. I am facing the same problem.. When video keeps recording and my screen is also in normal mode, it records successfully but as soon as my screen moves in idle mode or it gets locks, my video start to record in black screen(from that phase where screen locks)... please help me.

      Delete
    5. Do we the solution of above problem yet ? I am having same issue. Please help :)

      Delete
  18. Hi

    How I can change the type of video created, I want to save video as .wmv type.

    ReplyDelete
    Replies
    1. I am not sure how to change it in .wmv but you can try by changing argument "ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE"

      Delete
  19. How can i change the name of video file?

    ReplyDelete
    Replies
    1. For this you need to change "MyVideo" in method startRecording() of class VideoReord ().

      Delete
  20. Hi,

    This was a very nice article posted for those who wanted to perform this critical task.

    Thank You.

    BTW, I was looking for the similar type of tutorial for the MP4 Vidoes.
    If it is possible to record the video in MP4 then pls provide the updated code.


    Thanks,
    Jagjit

    ReplyDelete
    Replies
    1. I need a same requirement please help me anyone

      Delete
  21. Thanks for the nice post. Great Job done by you.........
    This really help me

    ReplyDelete
  22. Hi,
    can you help with this:
    Im getting:
    classNotFoundException javax.sound.sampled ?
    thanks
    yael

    ReplyDelete
    Replies
    1. It means you are missing some jar file. Can you send you file to me so that I can check error.
      My email ID: roadtoautomation@gmail.com

      Delete
  23. I am getting a black screen when I play back th e avi file, can you help if I am missing anything?

    ReplyDelete
  24. It works,Thank you very much

    ReplyDelete
  25. It works with individual test cases, how to record when i run a suite file with bunch of TC's using TestNG xml

    ReplyDelete
    Replies
    1. Call VideoReord videoReord = new VideoReord(); videoReord.startRecording(); i BeforeSuite or BeforeTest methods and this.screenRecorder.stop(); in AfterSuite or AfterTest methods.

      Delete
  26. Hi,

    I try to work with this and it works great when there is open remote desktop window to the vmware.
    When I minimize the remote desktop window or close it I got black screen.

    Can it be solved ?

    Thanks

    ReplyDelete
    Replies
    1. Don't use remote desktop to this server, use VNC and the video will always be fine, even when you quit your VNC session.

      Delete
    2. Hi Avi,

      Can you tell me how it worked for VM and have you used any CI to run your tests.?

      Delete
  27. Hi
    I am able to record videos and save them in desired location but unable to set the video name...above mentioned code in @Override didn't work...plus is it possible to directly pass the video name as a parameter in screenrecorder() format

    ReplyDelete
  28. Hi,
    I am able to record and save the video but unable to set the desired video name. Above metioned code in @Overide dint work..plus is there a way to pass video name directly as parameter in ScreenRecorder()...I mean without using @Override

    ReplyDelete
  29. Hey folks,

    I have a question. Video capture is perfect. But i would like to focus video capture only on testing application on browser rather than recording system activities. Anyone has got an idea and script for that. Please share with me. It would be very fine for my project.

    ReplyDelete
    Replies
    1. I too have the same question. Anyone having solutions ?

      Delete
  30. Thanks for this code now can you please send me the code of how to broadcast the saved video into some other system browser.
    my email id is kdsharma422@gmail.com

    ReplyDelete
  31. Thanks for the post its really helpful.

    ReplyDelete
  32. i am able to record the test by using your code.
    but how we can record the test for mobile automation ?

    ReplyDelete
    Replies
    1. Mirror your device with System and use same code to record

      Delete
    2. This comment has been removed by a blog administrator.

      Delete
  33. I am using Selenium and JAVA to write a test, after a while I decided to record my screen while the test is going on so I added Monte framework to my program and it is working like a charm. But at work I have two monitors and need to record both of them, and also I need to specify the path that I want this framework to save my record in.

    ReplyDelete
  34. Thanks. The screen recording works great.

    Wanted to ask- is there a way to record just the browser and not the entire screen?
    It will be useful when running parallel tests.
    It the example above it doesn't seem there is a way to pair the record and the driver.

    ReplyDelete
  35. Thanks. The screen recording works great.

    Wanted to ask- is there a way to record just the browser and not the entire screen?
    It will be useful when running parallel tests.
    It the example above it doesn't seem there is a way to pair the record and the driver.

    ReplyDelete
  36. video is not playing the screen is black kindly need a help

    ReplyDelete
  37. Nice Article. Looking for Mp4 format videos, Could you please share the MP4 format code ?

    ReplyDelete
  38. Thank you !, For me it is creating .avi file but it is not playing, if i convert it to mp4 then it is playing. do not know what is the issue, other regular .avi videos are playing correct. I embedded this avi in html ( video tag ) and not working on chrome browser, if i convert it to mp4, it is playing on chrome. So thinking in you can provide sample code to create mp4 videos it may work. thank you ! You are best !! Very nice Article.

    ReplyDelete
  39. Have a lot at this library https://github.com/SergeyPirogov/VideoRecorder/tree/modularRecorder

    ReplyDelete
  40. I am able to record video with this library.
    But when I run same scripts with jenkins server which is remote windows server, i am getting blank video.

    I have tried many workarounds but none of them worked.

    Help please

    ReplyDelete
    Replies
    1. am getting same issue, keep getting blank video when i run the test in jenkins

      Delete
    2. am getting same issue, keep getting blank video when i run the test in jenkins

      Delete
    3. Did you find a solution for this issue?

      Delete
  41. Is there any way to integrate this with nay other tool?
    for eg., I am trying to integrate with OATS tool

    ReplyDelete
  42. is there any commands for screen record in IOS like adb in Android

    ReplyDelete
  43. can we pause and resume recording in monte media library

    ReplyDelete

  44. When my test on jenkins the path for the video is as below by default
    http://172.30.17.121:3000/download_video/1dffd066-44d0-4b37-8124-e77e57d50b94.mp4

    but in this location i dont find any Videos folder.
    Can you please help me on this

    ReplyDelete

  45. When my test on jenkins the path for the video is as below by default
    http://172.30.17.121:3000/download_video/1dffd066-44d0-4b37-8124-e77e57d50b94.mp4

    but in this location i dont find any Videos folder.
    Can you please help me on this

    ReplyDelete
  46. Hi,
    Does it record execution of test scripts on mobile devices through Appium?

    Thanks

    ReplyDelete
    Replies
    1. it records your desktop. if you output displaying your device to desktop - it would be

      Delete
  47. Hi,

    Can you please help me know how can i implement using listener and using Testng.

    I have a Page Object Model framework built using Testng and
    i want to use this functionality @ listener level.

    Please suggest me.

    ReplyDelete
  48. Could give me a sample, where you use the audio?
    I would like to record the screen with audio.

    ReplyDelete
  49. Hi,

    I was Automate the selenium Script with video recording functions.
    The recording is working file and While play the video, the screen get blinked. Is this the issue with codec or something else. Currently I am running the script in Linux platform.
    Kindly help me out on this.

    ReplyDelete
  50. May it woks with Yii2? )) sorry for question )

    ReplyDelete
  51. Video is created successfully but it is not playing
    when I try to convert to .mp4 format it is showing invalid data..I am calling startRecording() in other class as

    public class HomeSteps extends DriverFactory {

    Logger log = Logger.getLogger("");
    VideoReord video = new VideoReord();

    @Given("^User is on Home page$")
    public void setUp() throws Exception {

    try {
    video.startRecording();
    log.info("Navigate to the https://yaskawa.microexcel.com/");
    driver.get("https://yaskawa.microexcel.com/");
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    } catch (NoSuchElementException e) {
    log.error("ERROR :Application is not getting launched");
    }

    }

    Please Help!

    ReplyDelete
  52. Video is Created successfully but not playing I am calling startRecording() method in different class as..

    public class HomeSteps extends DriverFactory {

    Logger log = Logger.getLogger("");
    VideoReord video = new VideoReord();

    @Given("^User is on Home page$")
    public void setUp() throws Exception {

    try {
    video.startRecording();
    log.info("Navigate to the https://yaskawa.microexcel.com/");
    driver.get("https://yaskawa.microexcel.com/");
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    } catch (NoSuchElementException e) {
    log.error("ERROR :Application is not getting launched");
    }

    }

    ReplyDelete
  53. Hi, Does this records active screen irrespective of whatever we do on the screen or it records execution even the browser in which tests are executing is at background. So that we can do our own stuff while execution and also able to look at execution video.

    ReplyDelete
  54. Great article..
    Does this code work for selenium grid, can you give more insights.
    Thanks in advance :)

    ReplyDelete
  55. Great Article....Code is Working very nice.....great blog....great post......

    ReplyDelete
  56. Hi
    For this if we should always open screen

    ReplyDelete
  57. Hi,

    For this, if we should open screen at all?

    ReplyDelete
  58. Hi there:

    Great post. It was really useful for me.

    I have a question: What about if the automated script is interrupted or goes down before the method stopRecording?

    How to do for generating the video even if the script is interrupted?

    Thanks in advance.

    ReplyDelete
  59. Video is getting overwrite.Could you please provide the solution?
    Thanks in advance.

    ReplyDelete
  60. I am running in linux envrionment and getting black video can someone please help me to resolve it

    ReplyDelete

Leave your comments, queries, suggestion I will try to provide solution