简体   繁体   English

Python RPI:如何动态调整当前播放的 wav 文件的音量

[英]Python RPI : How do i dynamically adjust the volume of my wav file currently playing

Currently using Raspberry Pi 3, pyaudio , ReSpeaker 2-Mics Pi HAT目前使用 Raspberry Pi 3, pyaudio , ReSpeaker 2-Mics Pi HAT

How do I adjust the volume of the .wav file playing using python in RPI?如何在 RPI 中使用 python 调整播放的 .wav 文件的音量? ( the output is through respeaker 3.5mm audio jack connected by an earpiece) (输出通过由听筒连接的扬声器 3.5mm 音频插孔输出)

I need the RPI to play and adjust the volume dynamically without needing me to change it manually我需要 RPI 来动态播放和调整音量,而无需我手动更改

Not accessing the alsamixer using the command in command prompt.不使用命令提示符中的命令访问 alsamixer。 Need some advice on how to proceed.需要一些有关如何进行的建议。

Below is the current progress of my code ( this code will be in a while loop playing ) :以下是我的代码的当前进度(此代码将在 while 循环中播放):

            filename ="output.wav"
            
            RESPEAKER_RATE = 16000
            RESPEAKER_CHANNELS = 2
            RESPEAKER_WIDTH = 2
            RESPEAKER_INDEX = 0  
            chunk = 1024
            wf = wave.open(filename, 'rb')
            p = pyaudio.PyAudio()
            stream = p.open(
                    format = p.get_format_from_width(RESPEAKER_WIDTH),
                    channels = RESPEAKER_CHANNELS,
                    rate = RESPEAKER_RATE,
                    output = True
                )
            
           
            
            data = wf.readframes(chunk)
            while data != '':
                stream.write(data)
                data = wf.readframes(chunk)
            
            stream.stop_stream()
            stream.close()
            p.terminate()

Tried this code but not really what I am trying to achieve尝试了这段代码,但并不是我真正想要实现的

Trying to change it whilst it is playing rather than changing it before尝试在播放时更改它而不是之前更改它

from pydub import AudioSegment

song = AudioSegment.from_wav("output.wav")
song = song - 60
quieter_song_data = song.get_array_of_samples()
quieter_song_fs = song.frame_rate4

In your play loop, compute the volume of the chunk (using root-mean-square, eg) and then if it is too high, divide.在您的播放循环中,计算块的体积(例如使用均方根),然后如果它太高,则除以。

For 8-bit audio (128 is neutral speaker position)对于 8 位音频(128 是中性扬声器位置)

data = wf.readframes(chunk)
while data != '':
    data2 = (data-128)/128) # now from -1 to 1
    volume = sum(data2 ** 2) ** .5
    if volume > .6:
        data = data2/volume * .6
        data = data*128 + 128
        data = [max(min(int(d),255),0) for d in data]
        # convert data back to type stream is happy with here if needed
    stream.write(data)
    data = wf.readframes(chunk)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM