python: audio

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""
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

  

posted @   ®Geovin Du Dream Park™  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2012-08-09 csharp DataTable and DataGridView delete a Row
2010-08-09 asp.net3.5 csharp Calendar 控件显示周次(1月周次问题)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示