I want to output the microphone input to the speaker.

Asked 2 years ago, Updated 2 years ago, 38 views

Questions about Python 3.x.
If the microphone does not have more than a certain amount of input for a certain period of time, the input is interrupted. I'm thinking of a program that outputs the audio input from the speaker.
However, we accept input, but we cannot output it.
Can someone help me?

import pyaudio
import path
import structure
import time

Threshold = 50

SHORT_NORMALIZE= (1.0/32768.0)
CHUNK = 8192
FORMAT=pyaudio.paInt16
CHANNELS = 1
RATE = 16000
width = 2

TIMEOUT_LENGTH = 1

p=pyaudio.PyAudio()

defrms(frame):
    count = len(frame) / width
    format = "%dh"%(count)
    shorts=struct.unpack (format, frame)

    sum_square=0.0
    for sample in shorts:
        n=sample*SHORT_NORMALIZE
        sum_square+=n*n
    rms=math.power(sum_square/count, 0.5)

    return rms*1000

stream=p.open(format=pyaudio.paInt16,
        channels = 1,
        rate = RATE,
        frames_per_buffer = CHUNK,
        input = True,
        output=True)# Make input and output both true at the same time

while stream.is_active():
    current=time.time()
    end=time.time()+TIMEOUT_LENGTH

    while current<=end:
        data=stream.read(CHUNK)

        ifrms(data)>=Threshold:
            end=time.time()+TIMEOUT_LENGTH
            print(rms(data))

        current=time.time()
        # output=stream.write(data)# Here the speaker will output sound (I don't want to write here)
        
    output=stream.write(data)# I want to output sound from the speaker here

stream.stop_stream()
stream.close()
p.terminate()

print ("Stop Streaming")

python python3

2022-09-30 12:09

1 Answers

Below are the answers in community wiki format written in the comments section.

After modifying the source code as follows, it worked as expected.

while stream.is_active():
    current=time.time()
    end=time.time()+TIMEOUT_LENGTH

    save_data=[]# To store input data
    while current<=end:
        data=stream.read(CHUNK)
        save_data.append(data)#Save Data

        ifrms(data)>=Threshold:
            end=time.time()+TIMEOUT_LENGTH
            print(rms(data))

        current=time.time()

    # output stored data
    for data in save_data:
        output=stream.write(data)


2022-09-30 12:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.