12

关于读取系统声级的最简单方法的任何线索是什么?

我计划创建一个由短 LED 灯带制成的均衡器,并将它们连接到 Arduino 或 RaspberryPi。我已经看到了很多例子,如何使用输入、麦克风等来做到这一点,但对于整体输出却没有那么多。在这一点上,我不在乎程序特定或系统范围,当我真正得到读数时我很高兴。欢迎任何建议。

- 编辑 -

基于如何从 python 中的麦克风获取声音输入,并即时处理它?我将 PCM_CAPTURE 更改为 PCM_PLAYBACK,这导致 python 说在输出/播放时无法读取。

我现在正在尝试创建一个环回设备,其想法是将播放传输回单独的捕获并读取它,但到目前为止还没有运气,我不知道这种方式有多整洁/干净。我真的无法想象这是要走的路。

4

3 回答 3

3

有人使用 Python 和 PulseAudio 实现了这一点,请参阅此博客文章。作者编写了一个脚本来轮询系统范围的峰值声级,以将其馈送到 VU 表。他还在 Bitbucket 上提供了源代码,请点击此处

我已经在 Ubuntu 上对其进行了测试,它对我有用(尽管只能从命令行,而不是在交互式 Python 会话中)。涉及的一些额外工作是安装用于与 Python 接口的 ctypes PulseAudio 包装器(源代码中的链接),并可能在脚本中将 SINK_NAME 设置为正确的值。

我从博客 PulseAudio 收集到的内容非常适合这项工作,但也许还有更好的方法。

于 2013-05-13T22:32:58.830 回答
0

几乎任何类型的混音器(软件或硬件)都应该能够将声音输出重新路由到输入。对于 Windows,有内置的Stereo Mix,对于 Linux,有几种解决方案(我听说过PulseAudio的好消息,但我无法证明自己——本教程中的一些步骤可能会有所帮助)。

这样你就可以将它路由到 Python - 你已经阅读的麦克风级别的示例应该也可以正常工作。

于 2013-05-04T02:35:38.840 回答
0

我找到了这个github 解决方案

mserve 鼠标按钮 hover.gif

我将 python 程序设置为一个单独的实例,这样它就不会落后于我的主程序。然后每 33 毫秒 (30 fps) 轮询 IPC 泡菜。我稍微修改了代码,如下所示:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#==============================================================================
#
#       vu_meter.py - Listen to microphone left/right and generate vu level
#
#==============================================================================
"""

FROM: https://github.com/kmein/vu-meter

.gitignore          NOT INSTALLED
LICENSE             NOT INSTALLED
README.md           NOT INSTALLED
amplitude.py                        THIS MODULE
record.py           NOT INSTALLED
vu_constants.py                     THIS MODULE
vu_meter.py                         THIS MODULE

ENHANCEMENTS:

    1) Support Python environment variable for automatic python 2 / 3 selection
    2) Add UTF-8 to support Python 2 (not necessary in this program though)
    3) Reset maximal between songs (gap when 10 samples of zero strength)
    4) Remove console output and write values to ramdisk (/run/user/1000)
    5) Optional 'stereo' parameter to measure left & right channels
    6) Utilize numpy which is usually auto-installed on distros
    7) Include separate amplitute.py & vu_constants.py in main
    8) Remove unused functions from Amplitude class

"""

from __future__ import print_function       # Must be first import
from __future__ import with_statement       # Error handling for file opens

import pyaudio
import numpy as np              # January 24, 2021 support separate 2 channels
import sys
import math
import struct
#from amplitude import Amplitude

RATE = 44100
INPUT_BLOCK_TIME = 0.05
INPUT_FRAMES_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME)
SHORT_NORMALIZE = 1.0 / 32768.0
# Mono output
VU_METER_FNAME  = "/run/user/1000/mserve.vu-meter-mono.txt"
# Stereo output (Left and Right)
VU_METER_LEFT_FNAME  = "/run/user/1000/mserve.vu-meter-left.txt"
VU_METER_RIGHT_FNAME  = "/run/user/1000/mserve.vu-meter-right.txt"


class Amplitude(object):
    ''' an abstraction for Amplitudes (with an underlying float value)
    that packages a display function and many more
    
    January 25, 2021 - Remove unused add, subb, gt, eq, int & str functions
    '''

    def __init__(self, value=0):
        self.value = value

    def __lt__(self, other):
        return self.value < other.value

    def to_int(self, scale=1):
        ''' convert an amplitude to an integer given a scale such that one can
        choose the precision of the resulting integer '''
        return int(self.value * scale)

    @staticmethod
    def from_data(block):
        ''' generate an Amplitude object based on a block of audio input data '''
        count = len(block) / 2
        shorts = struct.unpack("%dh" % count, block)
        sum_squares = sum(s**2 * SHORT_NORMALIZE**2 for s in shorts)
        return Amplitude(math.sqrt(sum_squares / count))

    def display(self, mark, scale=50, fn=VU_METER_FNAME):
        ''' display an amplitude and another (marked) maximal Amplitude
        graphically '''
        int_val = self.to_int(scale)
        mark_val = mark.to_int(scale)
        delta = abs(int_val - mark_val)
        # print(int_val * '*', (delta-1) * ' ', '|',mark_val,int_val,delta)
        # January 23, 2021: Write values to ramdisk instead of displaying
        with open(fn, "w") as vufile:
            vufile.write(str(mark_val) + " " + str(int_val))


def parse_data(data, channel_ndx, channel_cnt, maximal):
    '''
        Process data from one channel
    '''
    data = np.fromstring(data,dtype=np.int16)[channel_ndx::channel_cnt]
    data = data.tostring()
    amp = Amplitude.from_data(data)
    gap = amp.value      # For signal test below.
    if amp > maximal:
        maximal = amp
    return amp, maximal, gap


def main():

    # January 24, 2021 separate left and right channels
    parameter = 'mono'
    if (len(sys.argv)) == 2:
        parameter = sys.argv[1]     # Null = 'mono', 'stereo' = Left & Right

    audio = pyaudio.PyAudio()
    reset_baseline_count = 0
    try:
        stream = audio.open(format=pyaudio.paInt16,
                            channels=2,
                            rate=RATE,
                            input=True,
                            frames_per_buffer=INPUT_FRAMES_PER_BLOCK
                           )

        maximal = Amplitude()
        maximal_l = maximal_r = maximal

        while True:
            data = stream.read(INPUT_FRAMES_PER_BLOCK)

            # January 24, 2021 separate left and right channels
            if parameter == 'stereo':
                ampl, maximal_l, gap = parse_data(data, 0, 2, maximal_l)
                ampr, maximal_r, gap = parse_data(data, 1, 2, maximal_r)
                if maximal_r < maximal_l:
                    # A momentary spike to left channel inherited by right
                    maximal_r = maximal_l
                if maximal_l < maximal_r:
                    # A momentary spike to right channel inherited by left
                    maximal_l = maximal_r
            else:
                # Mono - processing all dadta
                amp = Amplitude.from_data(data)
                gap = amp.value      # For signal test below.
                if amp > maximal:
                    maximal = amp

            # New code January 23, to reset next song's maximal during gap
            if gap == 0.0:
                reset_baseline_count += 1
                if reset_baseline_count == 10:
                    maximal = Amplitude()
                    maximal_l = maximal_r = maximal
                    # print('maximual reset', maximal.value)
            else:
                reset_baseline_count = 0

            # January 24, 2021 separate left and right channels
            if parameter == 'stereo':
                ampl.display(scale=200, mark=maximal_l, fn=VU_METER_LEFT_FNAME)
                ampr.display(scale=200, mark=maximal_r, fn=VU_METER_RIGHT_FNAME)
            else:
                # Mono processing one channel combined sound
                amp.display(scale=200, mark=maximal, fn=VU_METER_FNAME)

    finally:
        stream.stop_stream()
        stream.close()
        audio.terminate()

if __name__ == "__main__":
    main()
于 2021-06-20T14:45:12.427 回答