脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 录制系统声音的示例

python 录制系统声音的示例

2021-08-16 00:29skyblue°sen Python

这篇文章主要介绍了python 录制系统声音的示例,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下

环境准备

python

  • wave
  • pyaudio

wave 可以通过pip直接install,在安装pyaudio时,通过正常的pip install 直接安装一直处于报错阶段,后来想到可以通过轮子直接安装。

在pypi提供的安装包中有对应的安装包,注意,不仅仅是python2和python3的区别,python3的小版本也有点差别。可杯具的是,小主电脑里装的是python3.8,后来想到还有一个网站可以安装pythonlibs,找到对应的版本后,下载下来。直接在文件所在目录,或者在安装中指定文件目录中执行安装

?
1
pip install /c/Users/root/Downloads/PyAudio-0.2.11-cp38-cp38-win_amd64.whl

代码和运行

?
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
def audio_record(out_file, rec_time):
  CHUNK = 1024
  FORMAT = pyaudio.paInt16 # 16bit编码格式
  CHANNELS = 1 # 单声道
  RATE = 16000 # 16000采样频率
  p = pyaudio.PyAudio()
  # 创建音频流
  dev_idx = findInternalRecordingDevice(p)
  stream = p.open(format=FORMAT, # 音频流wav格式
          channels=CHANNELS, # 单声道
          rate=RATE, # 采样率16000
          input=True,
          input_device_index=dev_idx, # 指定内录设备的id,可以不写,使用win的默认录音设备
          frames_per_buffer=CHUNK)
  print("Start Recording...")
  frames = [] # 录制的音频流
  # 录制音频数据
  for i in range(0, int(RATE / CHUNK * rec_time)): # 控制录音时间
    data = stream.read(CHUNK)
    frames.append(data)
  # 录制完成
  stream.stop_stream()
  stream.close()
  p.terminate()
  print("Recording Done...")
  # 保存音频文件
  wf = wave.open(out_file, 'wb')
  wf.setnchannels(CHANNELS)
  wf.setsampwidth(p.get_sample_size(FORMAT))
  wf.setframerate(RATE)
  wf.writeframes(b''.join(frames))
  wf.close()

在使用默认录音设备时,发现是话筒录音,效果并不是太理想,所以就去查查能不能直接录系统的声音。

?
1
2
3
4
5
6
7
8
9
10
11
12
def findInternalRecordingDevice(p):
  # 要找查的设备名称中的关键字
  target = '立体声混音'
  # 逐一查找声音设备
  for i in range(p.get_device_count()):
    devInfo = p.get_device_info_by_index(i)
    print(devInfo)
    if devInfo['name'].find(target) >= 0 and devInfo['hostApi'] == 0:
      # print('已找到内录设备,序号是 ',i)
      return i
  print('无法找到内录设备!')
  return -1

可以使用p.get_device_info_by_index()去查看系统有关声音的设备,通过设置为立体声混音就可以录制系统声音。

保存声音

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def save(fileName):
  # 创建pyAudio对象
  p = pyaudio.PyAudio()
  # 打开用于保存数据的文件
  wf = wave.open(fileName, 'wb')
  # 设置音频参数
  wf.setnchannels(CHANNELS)
  wf.setsampwidth(p.get_sample_size(FORMAT))
  wf.setframerate(RATE)
  # 写入数据
  wf.writeframes(b''.join(_frames))
  # 关闭文件
  wf.close()
  # 结束pyaudio
  p.terminate()

保存声音是通过上述代码进行保存,此处的_frames是个list,是通过每录一个chunk(数据流块),就把这一块的数据添加进去

然后只需要重新创建PyAudio对象,把这个list转为字节串保存到文件中就可以了

问题

上述一般可以录到系统声音,但在执行的时候发现,并不能。

原因是:win的输入设备中没有配置立体声混音

设置步骤:

  • 在win的声音调节出,右击打开声音设置
  • 找到管理声音设备
  • 在输入设备处启用立体声混音

就此,就完成了录制系统声音的需求

注意

上述操作,可以外放,可以插入3.5mm耳机,但系统静音和tpye-c耳机插入的时候不能录到声音

完整代码

?
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import os
import pyaudio
import threading
import wave
import time
from datetime import datetime
 
# 需要系统打开立体声混音
 
# 录音类
class Recorder():
  def __init__(self, chunk=1024, channels=2, rate=44100):
    self.CHUNK = chunk
    self.FORMAT = pyaudio.paInt16
    self.CHANNELS = channels
    self.RATE = rate
    self._running = True
    self._frames = []
 
  # 获取内录设备序号,在windows操作系统上测试通过,hostAPI = 0 表明是MME设备
  def findInternalRecordingDevice(self, p):
    # 要找查的设备名称中的关键字
    target = '立体声混音'
    # 逐一查找声音设备
    for i in range(p.get_device_count()):
      devInfo = p.get_device_info_by_index(i)
      # print(devInfo)
      if devInfo['name'].find(target) >= 0 and devInfo['hostApi'] == 0:
        # print('已找到内录设备,序号是 ',i)
        return i
    print('无法找到内录设备!')
    return -1
 
  # 开始录音,开启一个新线程进行录音操作
  def start(self):
    threading._start_new_thread(self.__record, ())
 
  # 执行录音的线程函数
  def __record(self):
    self._running = True
    self._frames = []
 
    p = pyaudio.PyAudio()
    # 查找内录设备
    dev_idx = self.findInternalRecordingDevice(p)
    if dev_idx < 0:
      return
    # 在打开输入流时指定输入设备
    stream = p.open(input_device_index=dev_idx,
            format=self.FORMAT,
            channels=self.CHANNELS,
            rate=self.RATE,
            input=True,
            frames_per_buffer=self.CHUNK)
    # 循环读取输入流
    while (self._running):
      data = stream.read(self.CHUNK)
      self._frames.append(data)
 
    # 停止读取输入流
    stream.stop_stream()
    # 关闭输入流
    stream.close()
    # 结束pyaudio
    p.terminate()
    return
 
  # 停止录音
  def stop(self):
    self._running = False
 
  # 保存到文件
  def save(self, fileName):
    # 创建pyAudio对象
    p = pyaudio.PyAudio()
    # 打开用于保存数据的文件
    wf = wave.open(fileName, 'wb')
    # 设置音频参数
    wf.setnchannels(self.CHANNELS)
    wf.setsampwidth(p.get_sample_size(self.FORMAT))
    wf.setframerate(self.RATE)
    # 写入数据
    wf.writeframes(b''.join(self._frames))
    # 关闭文件
    wf.close()
    # 结束pyaudio
    p.terminate()
 
 
if __name__ == "__main__":
 
  # 检测当前目录下是否有record子目录
  if not os.path.exists('record'):
    os.makedirs('record')
 
  print("\npython 录音机 ....\n")
  print("提示:按 r 键并回车 开始录音\n")
 
  i = input('请输入操作码:')
  if i == 'r':
    rec = Recorder()
    begin = time.time()
 
    print("\n开始录音,按 s 键并回车 停止录音,自动保存到 record 子目录\n")
    rec.start()
 
    running = True
    while running:
      i = input("请输入操作码:")
      if i == 's':
        running = False
        print("录音已停止")
        rec.stop()
        t = time.time() - begin
        print('录音时间为%ds' % t)
        # 以当前时间为关键字保存wav文件
        rec.save("record/rec_" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".wav")

以上就是python 录制系统声音的示例的详细内容,更多关于python 录制系统声音的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/ZSMblog/p/12376145.html

延伸 · 阅读

精彩推荐