zoukankan      html  css  js  c++  java
  • Python+opencv+pyaudio实现带声音屏幕录制

    原文链接:https://blog.csdn.net/zhaoyun_zzz/article/details/84341801

    Python+opencv+pyaudio实现带声音屏幕录制
    原创luke-skyworker 发布于2018-11-28 23:05:23 阅读数 3463 收藏
    展开
    文章目录
    声音录制
    视频录制(无声音)
    录制的音频与视频合成为带声音的视频

    基于个人的爱好和现实的需求,决定用Python做一个屏幕录制的脚本。因为要看一些加密的视频,每次都要登录,特别麻烦,遂决定用自己写的脚本,将加密视频的播放过程全程录制下来,这样以后看自己的录播就好了。结合近期自己学习的内容,正好用Python来练练手,巩固自己的学习效果。
    经过多番搜索,决定采用Python+opencv+pyaudio来实现屏幕录制。网上搜索到的录屏,基本都是不带声音的,而我要实现的是带声音的屏幕录制。下面就开始一步一步的实现吧。
    声音录制
    import pyaudio
    import wave
    import sys

    CHUNK = 1024
    if len(sys.argv) < 2:
    print("Plays a wave file. Usage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

    wf = wave.open(sys.argv[1], 'rb')
    p = pyaudio.PyAudio()
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
    channels=wf.getnchannels(),
    rate=wf.getframerate(),
    output=True)

    data = wf.readframes(CHUNK)
    while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)

    stream.stop_stream()
    stream.close()
    p.terminate()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    简洁回调函数版音频录制

    import pyaudio
    import wave
    import time
    import sys

    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 44100
    RECORD_SECONDS = 10
    WAVE_OUTPUT_FILENAME = "output.wav"

    p = pyaudio.PyAudio()
    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)

    time_count = 0
    def callback(in_data, frame_count, time_info, status):
    wf.writeframes(in_data)
    if(time_count < 10):
    return (in_data, pyaudio.paContinue)
    else:
    return (in_data, pyaudio.paComplete)

    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
    channels=wf.getnchannels(),
    rate=wf.getframerate(),
    input=True,
    stream_callback=callback)

    stream.start_stream()
    print("* recording")
    while stream.is_active():
    time.sleep(1)
    time_count += 1

    stream.stop_stream()
    stream.close()
    wf.close()
    p.terminate()
    print("* recording done!")
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    视频录制(无声音)
    from PIL import ImageGrab
    import numpy as np
    import cv2

    image = ImageGrab.grab()#获得当前屏幕
    width = image.size[0]
    height = image.size[1]
    print("", width, "height:", height)
    print("image mode:",image.mode)
    k=np.zeros((width,height),np.uint8)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')#编码格式
    video = cv2.VideoWriter('test.avi', fourcc, 25, (width, height))
    #输出文件命名为test.mp4,帧率为16,可以自己设置
    while True:
    img_rgb = ImageGrab.grab()
    img_bgr=cv2.cvtColor(np.array(img_rgb), cv2.COLOR_RGB2BGR)#转为opencv的BGR格式
    video.write(img_bgr)
    cv2.imshow('imm', img_bgr)
    if cv2.waitKey(1) & 0xFF == ord('q'):
    break
    video.release()
    cv2.destroyAllWindows()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    录制的音频与视频合成为带声音的视频
    录制200帧,带音频的MP4视频,单线程

    import wave
    from pyaudio import PyAudio,paInt16
    from PIL import ImageGrab
    import numpy as np
    import cv2
    from moviepy.editor import *
    from moviepy.audio.fx import all
    import time

    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 44100
    WAVE_OUTPUT_FILENAME = "output.wav"

    p = pyaudio.PyAudio()
    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    audio_record_flag = True
    def callback(in_data, frame_count, time_info, status):
    wf.writeframes(in_data)
    if audio_record_flag:
    return (in_data, pyaudio.paContinue)
    else:
    return (in_data, pyaudio.paComplete)
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
    channels=wf.getnchannels(),
    rate=wf.getframerate(),
    input=True,
    stream_callback=callback)
    image = ImageGrab.grab()#获得当前屏幕
    width = image.size[0]
    height = image.size[1]
    print("", width, "height:", height)
    print("image mode:",image.mode)
    k=np.zeros((width,height),np.uint8)

    fourcc = cv2.VideoWriter_fourcc(*'XVID')#编码格式
    video = cv2.VideoWriter('test.mp4', fourcc, 9.5, (width, height))
    #经实际测试,单线程下最高帧率为10帧/秒,且会变动,因此选择9.5帧/秒
    #若设置帧率与实际帧率不一致,会导致视频时间与音频时间不一致

    print("video recording!!!!!")
    stream.start_stream()
    print("audio recording!!!!!")
    record_count = 0
    while True:
    img_rgb = ImageGrab.grab()
    img_bgr=cv2.cvtColor(np.array(img_rgb), cv2.COLOR_RGB2BGR)#转为opencv的BGR格式
    video.write(img_bgr)
    record_count += 1
    if(record_count > 200):
    break
    print(record_count, time.time())

    audio_record_flag = False
    while stream.is_active():
    time.sleep(1)

    stream.stop_stream()
    stream.close()
    wf.close()
    p.terminate()
    print("audio recording done!!!!!")

    video.release()
    cv2.destroyAllWindows()
    print("video recording done!!!!!")

    print("video audio merge!!!!!")
    audioclip = AudioFileClip("output.wav")
    videoclip = VideoFileClip("test.mp4")
    videoclip2 = videoclip.set_audio(audioclip)
    video = CompositeVideoClip([videoclip2])
    video.write_videofile("test2.mp4",codec='mpeg4')
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    看来要提高帧率必须使用队列加多线程了,这一步等到以后来添加吧。不过总是觉得用OpenCV来实现视频录制,有点怪异,毕竟opencv是用来做图像与视频分析的,还是走正道认真捣鼓opencv该做的事情吧。
    ————————————————
    版权声明:本文为CSDN博主「luke-skyworker」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

  • 相关阅读:
    ASP.NET提供文件下载函数
    web.config access数据库相对路径设置方法 for asp.net2.0
    MSDE安装后身份验证自动是windows验证,osql命令中修改为sqlserve身份验证或混合验证呢及注冊表修改方法
    关于ASP.NET IIS的注册:
    指定datagrid编辑框的宽度及相映属性(转)备用
    TransparentListBox
    在dll中使用FastReport会遇到以下内个问题
    值得学习一
    注册表恢复默认共享
    有关dnn的安装不成功问题
  • 原文地址:https://www.cnblogs.com/shuimuqingyang/p/12130285.html
Copyright © 2011-2022 走看看