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
| #!/usr/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import pyaudio
from matplotlib.widgets import Button
buttons = []
def play(S):
fs = int(1/(S[1, 0] - S[0, 0]))
try:
p = pyaudio.PyAudio()
try:
stream = p.open(
format=pyaudio.paFloat32,
channels=1,
rate=fs,
output=True)
stream.write(S[:, 1].astype(np.float32))
finally:
stream.stop_stream()
stream.close()
finally:
p.terminate()
#############################################################################
# Création du signal
plt.figure(0)
#############################################################################
fs0 = 44100 # Freq d'échantillonage
f0 = 440.0 # Freq fondamentale
d0 = 10.0 # Durée du signal
nf0plot = 5 # Durée du signal pour les plots
TF0 = np.array([(f0, 1, 0)])#, (5*f0, 0.3, 0)])
def sample_S(fs, d=nf0plot*1/f0, TF=TF0):
T = np.arange(0, d, 1/fs)
S = np.zeros(len(T))
for f,a,p in TF:
S += a * np.cos(2*np.pi*f*T + p)
return np.stack((T, S), axis=-1)
S0 = sample_S(fs0)
#############################################################################
# Acquisition du signal
#############################################################################
nFS1 = [fs0/f0, 25, 8, 7, 3, 2, 1.9, 1.8]
for i,nfs1 in enumerate(nFS1):
plt.figure(i)
fs1 = nfs1 * f0
S1 = sample_S(fs1)
plt.suptitle('fs = %s*f0 = %s Hz, f0 = %s Hz' % (nfs1, fs1, f0))
# Plot signal
plt.subplot(311)
plt.plot(S0[:, 0], S0[:, 1])
if i != 0:
plt.plot(S1[:, 0], S1[:, 1], linestyle='dotted')
plt.stem(S1[:, 0], S1[:, 1], basefmt='None', markerfmt='.r', linefmt='r')
# Plot TF
plt.subplot(312)
if i != 0:
TF1A = np.abs(np.fft.fft(S1[:, 1]))
TF1A = TF1A / np.max(TF1A)
TF1P = np.angle(np.fft.fft(S1[:, 1]))
TF1F = np.arange(len(TF1A))*fs1/len(TF1A)
plt.stem(TF1F, TF1A, basefmt='None', markerfmt='r.', linefmt='r')
TF1 = np.stack((TF1F, TF1A, TF1P), axis=-1)
else:
plt.stem(TF0[:, 0], TF0[:, 1], basefmt='None', markerfmt='r.', linefmt='r')
TF1 = TF0
fplot = 10
plt.xlim(0, fplot*f0)
plt.xticks([i*f0 for i in range(fplot)], [0] + ['%s*f0'%i for i in range(1, fplot)])
# Plot signal reconstruit
TF1 = TF1[0:int(len(TF1)/2)+1]
S2 = sample_S(fs0, TF=TF1)
plt.subplot(313)
plt.plot(S0[:, 0], S0[:, 1], linestyle='dotted')
if i != 0:
plt.plot(S1[:, 0], S1[:, 1], linestyle='dotted')
plt.plot(S2[:, 0], S2[:, 1], color='r')
# Boutons
buttons.append(Button(plt.axes([0, 0, 0.1, 0.1]), 'Play'))
buttons[-1].on_clicked(lambda x, TFX=TF1: play(sample_S(fs0, 5.0, TF=TFX)))
plt.show()
|