Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
录制和播放音频-python_Python_Pyaudio - Fatal编程技术网

录制和播放音频-python

录制和播放音频-python,python,pyaudio,Python,Pyaudio,我将使用python实现一个语音聊天。所以我看了几个例子,如何播放声音和如何录音。在许多示例中,他们使用了pyAudio库。 我能够录制语音并将其保存在.wav文件中。我可以播放.wav文件。但我正在寻找5秒钟的录音,然后播放。我不想把它保存到文件中然后再播放,这不适合语音聊天 这是我的录音代码: p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=1, rate=RATE, input=True,

我将使用python实现一个语音聊天。所以我看了几个例子,如何播放声音和如何录音。在许多示例中,他们使用了
pyAudio
库。
我能够录制语音并将其保存在
.wav
文件中。我可以播放
.wav
文件。但我正在寻找5秒钟的录音,然后播放。我不想把它保存到文件中然后再播放,这不适合语音聊天

这是我的录音代码:

p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=1, rate=RATE,
        input=True, output=True,
        frames_per_buffer=CHUNK_SIZE)
num_silent = 0
snd_started = False

r = array('h')

while 1:
    # little endian, signed short
    snd_data = array('h', stream.read(CHUNK_SIZE))
    if byteorder == 'big':
        snd_data.byteswap()
    r.extend(snd_data)

    silent = is_silent(snd_data)

    if silent and snd_started:
        num_silent += 1
    elif not silent and not snd_started:
        snd_started = True

    if snd_started and num_silent > 30:
        break
现在我想在不保存的情况下玩它。我不知道怎么做

通过查看,您已经得到了它应该有的一切,但您忘记的是,
是一个双工描述符。这意味着您可以从中读取以录制声音(就像您使用
stream.read
)和写入以播放声音(使用
stream.write

因此,示例代码的最后几行应该是:

# Play back collected sound.
stream.write(r)

# Cleanup the stream and stop PyAudio
stream.stop_stream()
stream.close()
p.terminate()

我不喜欢这个库,请尝试使用“
sounddevice
”和“
soundfile
”它非常易于使用和实现。 要录制和播放语音,请使用以下选项:

import sounddevice as sd
import soundfile as sf 


sr = 44100
duration = 5
myrecording = sd.rec(int(duration * sr), samplerate=sr, channels=2)
sd.wait()  
sd.play(myrecording, sr)
sf.write("New Record.wav", myrecording, sr)