python: audio
"""
python.exe -m pip install --upgrade pip
pip install pyaudio
pip install matplotlib
https://matplotlib.org/3.1.1/gallery/animation/simple_anim.html
https://matplotlib.org/stable/api/figure_api.html
"""
# encoding: utf-8
# 版权所有 2023 涂聚文有限公司
# 许可信息查看:
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 311
# Datetime : 2023/8/9 21:03
# User : geovindu
# Product : PyCharm
# Project : pythonTkinterDemo
# File : AudioHelper.py
# explain : 学习
import pyaudio
import wave
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
class audioHelper(object):
"""
if __name__ == '__main__':
# 录制5s的声音
getAudio(5)
# 播放声音
play_audio('录音.wav')
# 录制5s的音乐
fig, line = plotInit()
# 播放音乐
play_audio('录音.wav')
"""
def __init__(self):
"""
"""
def getAudio(slef,sec):
"""
录音
:return:
"""
# 创建对象
p = pyaudio.PyAudio()
# 创建流:采样位,声道数,采样频率,缓冲区大小,input=True
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024)
# 创建式打开音频文件
wf = wave.open('录音.wav', 'wb')
# 设置声道数
wf.setnchannels(1)
# 设置采样位数
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wf.setframerate(16000)
print('开始录音')
for w in range(int(16000 * sec / 1024)):
data = stream.read(1024)
wf.writeframes(data)
print('录音结束')
stream.stop_stream()
stream.close()
p.terminate()
wf.close()
# return 'test.wav'
def play_audio(self,file):
"""
播放音乐
:return:
"""
p = pyaudio.PyAudio()
wf = wave.open(file, 'rb')
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True
)
data = wf.readframes(1024)
while len(data) > 0:
stream.write(data)
data = wf.readframes(1024)
stream.stop_stream()
stream.close()
p.terminate()
wf.close()
def play_audio(sslf,file):
"""
播放音乐
:return:
"""
fig, ax = plt.subplots()
x = np.arange(0, 2 * np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
p = pyaudio.PyAudio()
wf = wave.open(file, 'rb')
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True
)
data = wf.readframes(1024)
while len(data) > 0:
stream.write(data)
data = wf.readframes(1024)
data = np.frombuffer(data, dtype=np.int16)
if len(data) <= 0:
break
print(data)
line.set_ydata(data)
fig.canvas.draw()
fig.canvas.flush_events()
plt.pause(0.01)
stream.stop_stream()
stream.close()
p.terminate()
wf.close()
def plotInit(self):
"""
录制5s的音乐
:return:
"""
CHUNK = 1024
mpl.rcParams['toolbar'] = 'None'
fig, ax = plt.subplots(figsize=(12, 3))
ax.set_xlim(0, CHUNK - 1)
ax.set_ylim(-2 ** 15, 2 ** 15)
plt.subplots_adjust(left=0.001, top=0.999, right=0.999, bottom=0.001)
plt.get_current_fig_manager().set_window_title('wave')
x = np.arange(0, CHUNK)
line, = ax.plot(x, np.random.rand(CHUNK), color='#C04851')
plt.axis('off')
plt.ion()
plt.show()
return fig, line
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)