stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024)
时间: 2023-10-08 20:08:19 浏览: 66
这段代码使用 PyAudio 库创建了一个音频流,其中:
- `format=pyaudio.paInt16` 表示音频格式为 16 位整数;
- `channels=1` 表示音频通道数为 1;
- `rate=16000` 表示音频采样率为 16000 Hz;
- `input=True` 表示创建输入流,即从麦克风等输入设备读取音频数据;
- `frames_per_buffer=1024` 表示每次读取音频数据的帧数为 1024,即每次读取 1024 个采样点的音频数据。
相关问题
self.stream = self.p.open(format = FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) while self.stream.is_active(): frames = [] for i in range(0,int(RATE / CHUNK * RECORED_SECONDS)): data = self.stream.read(CHUNK) frames.append(data) senddata = pickle.dumps(frames) try: self.sock.sendall(struct.pack("L",len(senddata))+senddata) except: 修改代码实现变声
要实现变声,你可以使用PyAudio库提供的`effects`模块,其中包含了一些变声效果的函数,比如`chipmunk`、`robot`、`man`等。你可以在读取音频数据的时候,对数据应用这些变声效果。
下面是一个简单的实现示例,该示例将音频数据变成小矮人的声音:
```python
import pyaudio
from pydub import AudioSegment
from pydub.effects import speedup
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = 5
SPEEDUP_FACTOR = 2.0
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
# 将音频数据转换为PyDub的音频片段
audio_segment = AudioSegment(
data=b''.join(frames),
sample_width=p.get_sample_size(FORMAT),
frame_rate=RATE,
channels=CHANNELS
)
# 变声
audio_segment = audio_segment.speedup(
playback_speed=SPEEDUP_FACTOR,
chunk_size=CHUNK,
crossfade=10
)
# 将变声后的音频片段转换回PyAudio可播放的数据
data = audio_segment.raw_data
stream.stop_stream()
stream.close()
p.terminate()
```
需要注意的是,这里使用了`pydub`库进行音频变声。在使用之前,你需要先安装它,可以使用以下命令进行安装:
```bash
pip install pydub
```
import os import random import time from fnmatch import fnmatch import pygame import tkinter as tk from tkinter import * import wave import threading import tkinter import tkinter.filedialog import tkinter.messagebox import pyaudio root = tk.Tk() root.geometry("450x200+374+182") root.title("英语单词") english1 = "开始" w = Label(root, font=('times', 20, 'bold'), text=english1) w.pack() timer_running = False def word(): path = "D:\MY python\English" lists = os.listdir(path) english = (random.choice(lists)) global english1 english1 = english.strip(".wav") time.sleep(3) basedir = r"D:\MY python\English" for root, dirs, files in os.walk(basedir): for file in files: english3 = os.path.join(root, file) if fnmatch(file, f"{english1}*.wav"): pygame.mixer.init() pygame.mixer.music.load(english3) pygame.mixer.music.play() w.configure(text=f"{english1}") w.after(100, word) fileName = None allowRecording = False CHUNK_SIZE = 1024 CHANNELS = 2 FORMAT = pyaudio.paInt16 RATE = 44100 def record(): global fileName p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK_SIZE) wf = wave.open(fileName, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) while allowRecording: data = stream.read(CHUNK_SIZE) wf.writeframes(data) wf.close() stream.stop_stream() stream.close() p.terminate() fileName = None def start(): global allowRecording, fileName fileName = tkinter.filedialog.asksaveasfilename(filetypes=[('未压缩波形文件', '*.wav')]) if not fileName: return if not fileName.endswith('.wav'): fileName = fileName + '.wav' allowRecording = True start_timer() lbStatus['text'] = '正在录音中...' threading.Thread(target=record).start() def stop(): global allowRecording allowRecording = False lbStatus['text'] = '录音已结束' stop_timer() def closeWindow(): if allowRecording: tkinter.messagebox.showerror('Recording', 'Please stop recording before close the window.') return root.destroy() def tick(): global sec sec += 1 time['text'] = sec # Take advantage of the after method of the Label if timer_running: time.after(1000, tick) def start_timer(): global timer_running timer_running = True tick() def stop_timer(): global timer_running, sec timer_running = False sec = 0 time['text'] = sec button = tk.Button(text="开始", command=word) button.pack() btnStart = tkinter.Button(root, text='开始录音', command=start) btnStart.pack() btnStop = tkinter.Button(root, text='结束录音', command=stop) btnStop.pack() lbStatus = tkinter.Label(root, text='录音已准备', anchor='w', fg='green') lbStatus.pack() root.protocol('WM_DELETE_WINDOW', closeWindow) time = Label(root, fg='green') time.pack() root.mainloop()
要实现点击按钮退出并重置时间,可以在按钮的命令函数中添加退出和重置时间的功能。以下是修改的代码示例:
```python
import os
import random
import time
from fnmatch import fnmatch
import pygame
import tkinter as tk
from tkinter import *
import wave
import threading
import tkinter
import tkinter.filedialog
import tkinter.messagebox
import pyaudio
root = tk.Tk()
root.geometry("450x200+374+182")
root.title("英语单词")
english1 = "开始"
w = Label(root, font=('times', 20, 'bold'), text=english1)
w.pack()
timer_running = False
def word():
path = "D:\MY python\English"
lists = os.listdir(path)
english = (random.choice(lists))
global english1
english1 = english.strip(".wav")
time.sleep(3)
basedir = r"D:\MY python\English"
for root, dirs, files in os.walk(basedir):
for file in files:
english3 = os.path.join(root, file)
if fnmatch(file, f"{english1}*.wav"):
pygame.mixer.init()
pygame.mixer.music.load(english3)
pygame.mixer.music.play()
w.configure(text=f"{english1}")
w.after(100, word)
fileName = None
allowRecording = False
CHUNK_SIZE = 1024
CHANNELS = 2
FORMAT = pyaudio.paInt16
RATE = 44100
def record():
global fileName
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK_SIZE)
wf = wave.open(fileName, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
while allowRecording:
data = stream.read(CHUNK_SIZE)
wf.writeframes(data)
wf.close()
stream.stop_stream()
stream.close()
p.terminate()
fileName = None
def start():
global allowRecording, fileName
fileName = tkinter.filedialog.asksaveasfilename(filetypes=[('未压缩波形文件', '*.wav')])
if not fileName:
return
if not fileName.endswith('.wav'):
fileName = fileName + '.wav'
allowRecording = True
start_timer()
lbStatus['text'] = '正在录音中...'
threading.Thread(target=record).start()
def stop():
global allowRecording
allowRecording = False
lbStatus['text'] = '录音已结束'
stop_timer()
def closeWindow():
if allowRecording:
tkinter.messagebox.showerror('Recording', 'Please stop recording before close the window.')
return
stop_timer() # 停止计时器
root.destroy()
def tick():
global sec
sec += 1
time['text'] = sec
# Take advantage of the after method of the Label
if timer_running:
time.after(1000, tick)
def start_timer():
global timer_running, sec
sec = 0 # 重置时间
timer_running = True
tick()
def stop_timer():
global timer_running, sec
timer_running = False
sec = 0
time['text'] = sec
button = tk.Button(text="开始", command=word)
button.pack()
btnStart = tkinter.Button(root, text='开始录音', command=start)
btnStart.pack()
btnStop = tkinter.Button(root, text='结束录音', command=stop)
btnStop.pack()
lbStatus = tkinter.Label(root, text='录音已准备', anchor='w', fg='green')
lbStatus.pack()
root.protocol('WM_DELETE_WINDOW', closeWindow)
time = Label(root, fg='green')
time.pack()
root.mainloop()
```
在上面的代码中,我添加了一个 `stop_timer` 函数来停止计时器并重置时间。在 `stop` 函数中调用 `stop_timer` 函数来停止计时器。同时,在 `closeWindow` 函数中也调用了 `stop_timer` 函数来确保在关闭窗口之前停止计时器。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)