0

I am trying the following code:

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()

but the Preview callback message is printed only one time. What's wrong with the code?

Edit: With the Sine signal the preview callback message is printed correctly and i can hear the sine sound.

Chris P
  • 2,059
  • 4
  • 34
  • 68

1 Answers1

0
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)

The above code instead of physical silence, uses a sine signal. In this signal we change the volume (-200db =~ silence), and then the code seems to work.

Warning: There is a better solution so search before use mine.

Chris P
  • 2,059
  • 4
  • 34
  • 68