how to record voice with screen recording in python

Viewed 4060

I am making an screen recorder in python in this i am sucessfull in capturing the screen with python PIL library.

And displaying it in the label (current recording).

Now what i want is to record audio from user when user click audio rec button in my GUI window and stop recording voice when user clicks on stop record voice button.

And finally i want to merge my voice and video recording to a final output as a video with voice

Can anyone tell me how can merge both the code in one single script and run it sucessfully.

import datetime
import tkinter as tk
from tkinter import *
from tkinter import ttk ,FLAT
from PIL import Image, ImageTk, ImageGrab
import cv2
import numpy as np
import threading
import win32api
from tkinter.filedialog import asksaveasfilename


VIDEO_SIZE = (800,420)     #(960, 540)

cap = cv2.VideoCapture(0) 

date = datetime.datetime.now()
filename='rec_%s-%s-%s-%s%s%s.mp4' % (date.year, date.month, date.day,
                                                     date.hour, date.minute, date.second)

fourcc = cv2.VideoWriter_fourcc(*'H264')
frame_rate = 15

out = cv2.VideoWriter()
def change_i():
        if sound_btn.image == icon:
            start_recording()

            sound_btn.config(image=icon2)
            sound_btn.image = icon2
        else:
            stop_recording()

            sound_btn.config(image=icon)
            sound_btn.image = icon

def change_r():
        if rec_btn['text'] == 'Start Recording':
            start_recording()

            rec_btn.config(text="Stop Recoding")
        else:
            stop_recording()

            rec_btn.config(text="Start Recording")
def change_w():
        if cap_btn.image == web:
            start_webcam()

            cap_btn.config(image=web2)
            cap_btn.image = web2
        else:
            stop_webcam(None)

            cap_btn.config(image=web)
            cap_btn.image = web
# --- screen capture
def Cursor_pos(img,center,radius,color,thickness):
    center = tuple(map(int,center))
    rgb = [255*c for c in color[:3]] # convert to 0-255 scale for OpenCV
    alpha = color[-1]
    radius = int(radius)
    if thickness > 0:
        pad = radius + 2 + thickness
    else:
        pad = radius + 3
    roi = slice(center[1]-pad,center[1]+pad),slice(center[0]-pad,center[0]+pad)

    try:
        overlay = img[roi].copy()
        cv2.circle(img,center,radius,rgb, thickness=thickness, lineType=cv2.LINE_AA)
        opacity = alpha
        cv2.addWeighted(src1=img[roi], alpha=opacity, src2=overlay, beta=1. - opacity, gamma=0, dst=img[roi])
    except:
        logger.debug("transparent_circle would have been partially outside of img. Did not draw it.")

def recording_screen():

    global recording
    recording = True
    while recording:0,0.5), -1)
        #cv2.circle(frame, curpos, 10, (0,255,255), 2)
        frame = cv2.resize(frame, VIDEO_SIZE)
        tkimage.paste(Image.fromarray(frame))
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        out.write(frame)

def start_recording():

    if not out.isOpened():
    out.open(filename, fourcc, frame_rate, VIDEO_SIZE)
    threading.Thread(target=recording_screen, daemon=True).start()

def stop_recording():
    global recording
    recording = False
    out.release()

# --- webcam

webcam = None
WEBCAM_SIZE = (280, 200)

def read_frame(imgbox):

    if cap.isOpened():
        ret, frame = cap.read()
        if ret:
            frame = cv2.flip(frame, 1)
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = cv2.resize(frame, WEBCAM_SIZE)
            image = Image.fromarray(frame)
            imgbox.image.paste(image)
        webcam.after(20, read_frame, imgbox)

def stop_webcam(event):
    global webcam

    if webcam:
        webcam.destroy()
        webcam = None
        cap.release()
def start_webcam():
    global webcam

    if webcam is None:
        cap.isOpened()
        webcam = tk.Toplevel()
        #webcam = tk.lift()
        webcam.attributes("-topmost", True) #it keep the window on top of others
        webcam.geometry('{}x{}+5+520'.format(WEBCAM_SIZE[0], WEBCAM_SIZE[1]))
        webcam.overrideredirect(1)
        imgbox = tk.Label(webcam)
        imgbox.pack()
        imgbox.image = ImageTk.PhotoImage(image=Image.new('RGB',WEBCAM_SIZE,(0,0,0)))
        imgbox.config(image=imgbox.image)
        #webcam.bind('', stop_webcam)
        read_frame(imgbox)

# --- main

root = tk.Tk()
root.title('Screen Recorder')
#root.iconbitmap(r'rec_i.ico')  #for icon
root.resizable(width=False,height=False)
icon = PhotoImage(file='dh.png')
icon2 = PhotoImage(file='stop.png')
web = PhotoImage(file='webcam.png')
web2 = PhotoImage(file='webcamee.png')
root.geometry('+260+70')

tkimage = ImageTk.PhotoImage(Image.new('RGB', VIDEO_SIZE, (0,0,0)))


w, h = VIDEO_SIZE
vbox = tk.Label(root, image=tkimage, width=w, height=h, bg='black')
vbox.pack(pady=10,padx=25)

frame = tk.Frame(root)
frame.pack()

ound_btn = tk.Button(frame, image=icon, width=70,relief=FLAT ,command=change_i )
sound_btn.grid(row=0, column=1)
sound_btn.image = icon
cap_btn = tk.Button(frame, image=web, width=70,relief=FLAT, command=change_w)
cap_btn.grid(row=0, column=2)
cap_btn.image = web
message = Label(frame,text='**** press the start button to start recording ****')
message.grid(row=1, column=1)

root.mainloop()

what can i do to record voice of a user through microphone while recording screen simentenusly.

Any suggestion ?

1 Answers

You can just simply record screen and as well as your voice in same script . That code will produce two files one is .mp4 and other is .mp3 ,Now you are set to go... add that audio file to the video file and save to path.

Related