简体   繁体   English

录制和播放音频-Python

[英]Record and play audio - python

I'm going to implement a voice chat using python. 我将使用python实现语音聊天。 So I saw few examples, how to play sound and how to record. 所以我看到了几个例子,如何播放声音和如何录音。 In many examples they used pyAudio library. 在许多示例中,他们使用了pyAudio库。
I'm able to record voice and able to save it in .wav file. 我能够录制语音并将其保存为.wav文件。 And I'm able play a .wav file. 而且我可以播放.wav文件。 But I'm looking for record voice for 5 seconds and then play it. 但是我正在寻找录音5秒钟然后播放。 I don't want to save it into file and then playing, it's not good for voice chat. 我不想将其保存到文件中然后再播放,这对语音聊天不利。

Here is my audio record code: 这是我的录音记录代码:

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

Now I want to play it without saving. 现在,我想不保存就播放它。 I don't know how to do it. 我不知道该怎么做。

Having looked through the PyAudio Documentation , you've got it all as it should be but what you're forgetting is that stream is a duplex descriptor. 浏览了PyAudio文档后 ,您已经了解了所有内容,但您忘记的是stream是一个双工描述符。 This means that you can read from it to record sound (as you have done with stream.read ) and you write to it to play sound (with stream.write ). 这意味着您可以从中读取声音以录制声音(如对stream.read所做的stream.read ),并对其进行写入以播放声音(与stream.write )。

Thus the last few lines of your example code should be: 因此,示例代码的最后几行应为:

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

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

I do not like this library try ' sounddevice ' and ' soundfile 'its are very easy to use and to implement. 我不喜欢这个库尝试“ sounddevice ”和“ soundfile ”它非常容易使用和实施。 for record and play voice use this: 要录制和播放声音,请使用以下命令:

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)

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

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