python 如何指定Pyaudio录制的音频文件的保存路径

zpgglvta  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(163)

我正在尝试找出一种方法,为要保存的录制文件设置本地目录的自定义路径。当前,录制保存在项目目录中,但我希望为其指定其他文件夹。

def record_audio():
filename =test 
chunk = 1024
FORMAT = pyaudio.paInt16
channels = 1
sample_rate = 16000
record_seconds = 5
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=channels,
                rate=sample_rate,
                input=True,
                output=True,
                frames_per_buffer=chunk)
frames = []
for i in range(int(sample_rate / chunk * record_seconds)):
    data = stream.read(chunk)
    # stream.write(data)
    frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
st.write("Finished recording.")
wf = wave.open(filename, "wb")
# set the channels
wf.setnchannels(channels)
# set the sample format
wf.setsampwidth(p.get_sample_size(FORMAT))
# set the sample rate
wf.setframerate(sample_rate)
# write the frames as bytes
wf.writeframes(b"".join(frames))
# close the file
wf.close()
toe95027

toe950271#

只要声明一个文件变量并指定路径,你就可以找到它,无论你是在Windows上使用命令行作为CD还是在UNIX上使用命令行作为PWD。最后,你在写wav的时候声明它,就这样。
就像这样:

var filepath: '/home/root/Projects/audios/filename.wav'

waveFile = wave.open(filepath, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(data)
waveFile.close()

相关问题