代码如下:
使用pyinstaller编译成exe即可
import pyaudio
import wave
import ctypes,operator
#pyaudio录音,播放参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 7
WAVE_OUTPUT_FILENAME = "output1.wav"
#设置声音参数
WM_APPCOMMAND = 0x319
APPCOMMAND_VOLUME_UP = 0x0a #增加音量
APPCOMMAND_VOLUME_DOWN = 0x09 #减少音量
APPCOMMAND_VOLUME_MUTE = 0x08 #静音
#将音量设置到最大
def setSpeakerVol():
hwnd = ctypes.windll.user32.GetForegroundWindow()
# print(hwnd)
ctypes.windll.user32.PostMessageA(hwnd, WM_APPCOMMAND, 0, APPCOMMAND_VOLUME_UP * 0x10000)
#录音
def record():
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
#播放上次录音文件
def play1():
#chunk = 1024 # 2014kb
wf = wave.open(r"output.wav", 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(),
rate=wf.getframerate(), output=True)
data = wf.readframes(CHUNK) # 读取数据
#print(data)
while data != 'b\'\'': # 播放
stream.write(data)
data = wf.readframes(CHUNK)
print('我要oupao,我要oupao,oupao果奶要要要')
#print(data)
stream.stop_stream() # 停止数据流
stream.close()
p.terminate() # 关闭 PyAudio
print('play函数结束!')
#播放指定文件
def play2():
chunk = 1024 # 2014kb
while True:
wf = wave.open(r"output.wav", 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(),
rate=wf.getframerate(), output=True)
data = wf.readframes(chunk) # 读取数据
while True:
setSpeakerVol()
data = wf.readframes(chunk)
if data == b'': #结束,如果需要循环播放,将if去掉即可
break
stream.write(data)
#print(1)
stream.stop_stream() # 停止数据流
stream.close()
p.terminate() # 关闭 PyAudio
print('play函数结束!')
if __name__ == '__main__':
#audio_file = 'output.wav' # 指定录音文件
record()
play2() # 播放录音文件