带有静音片段的 Pyaudio
Posted
技术标签:
【中文标题】带有静音片段的 Pyaudio【英文标题】:Pyaudio with silent segments 【发布时间】:2021-09-09 17:07:44 【问题描述】:我正在尝试以下代码:
import pyaudio
from pydub import Audiosegment,generators
import time
silence = AudioSegment.silent(duration=125,frame_rate=32768)
sine_data = generators.Sine(1000).to_audio_segment().raw_data
chunk_number = 0
def preview_callback(in_data, frame_count, time_info, status):
global chunk_number
print("Preview callback")
chunk_number +=1
print(chunk_number)
if chunk_number<10:
return (silence.raw_data,pyaudio.paContinue)
else:
return (sine_data,pyaudio.paContinue)
#QoS settings
bit_rate = 128*1024 #128 kb/sec
packet_time = 125 #125 msec
packet_size = int(16384/4)
new_sample_rate = 32768
format = pyaudio.paInt16
channels = 2
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,channels=2,rate=new_sample_rate,output=True,frames_per_buffer=packet_size,stream_callback=preview_callback)
stream.start_stream()
但Preview callback
消息只打印一次。
代码有什么问题?
编辑:使用正弦信号,预览回调消息打印正确,我可以听到正弦声音。
【问题讨论】:
【参考方案1】:import pyaudio
from pydub import AudioSegment,generators
import time
sine_segment = generators.Sine(1000).to_audio_segment()
sine_segment = sine_segment-200
sine_data = sine_segment.raw_data
def preview_callback(in_data, frame_count, time_info, status):
print("Preview callback")
return (sine_data,pyaudio.paContinue)
#QoS settings
bit_rate = 128*1024 #128 kb/sec
packet_time = 125 #125 msec
packet_size = int(16384/4)
new_sample_rate = 32768
format = pyaudio.paInt16
channels = 2
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,channels=2,rate=new_sample_rate,output=True,frames_per_buffer=packet_size,stream_callback=preview_callback)
stream.start_stream()
while(True):
print(stream.is_active())
print(stream.is_stopped())
time.sleep(2)
上面的代码不是物理静音,而是使用正弦信号。在这个信号中我们改变音量(-200db =~静音),然后代码似乎工作了。
警告:有更好的解决方案,所以在使用我的之前先搜索一下。
【讨论】:
以上是关于带有静音片段的 Pyaudio的主要内容,如果未能解决你的问题,请参考以下文章
使用带有silencedetect的FFMPEG来消除音频静音