-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
94 lines (78 loc) · 2.34 KB
/
main.py
File metadata and controls
94 lines (78 loc) · 2.34 KB
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
from numpy.fft import fft
from scipy import signal
from scipy.fft import fftshift
import matplotlib.pyplot as plt
import numpy as np
import json
from scipy.io import wavfile
from os import path
from pydub import AudioSegment
# import files
src = "assets/piano2.wav"
# dst = "test.wav"
dst = "assets/piano3.wav"
print("converting to wav file...")
# sound = AudioSegment.from_mp3(src)
# sound = sound.set_channels(1)
# sound.export(dst, format="wav")
sound = AudioSegment.from_wav(src)
print(sound.duration_seconds)
sound = sound.set_channels(1)
sound = sound.set_frame_rate(5000) # sample rate in kHz
sound.export(dst, format="wav")
print("importing wav file...")
sample_rate, samples = wavfile.read(dst)
print(f"sample_rate:\n{sample_rate}")
print(f"samples:\n{samples}")
print(len(samples))
# sample_rate = len(samples)
# print(samples.tolist())
# !
rng = np.random.default_rng()
# # Generate a test signal, a 2 Vrms sine wave whose frequency is slowly modulated around 3kHz, corrupted by white noise of exponentially decreasing magnitude sampled at 10 kHz.
fs = 10e3
N = 1e5
amp = 2 * np.sqrt(2)
noise_power = 0.01 * fs / 2
time = np.arange(N) / float(fs)
mod = 500*np.cos(2*np.pi*0.25*time)
carrier = amp * np.sin(2*np.pi*3e3*time + mod)
noise = rng.normal(scale=np.sqrt(noise_power), size=time.shape)
noise *= np.exp(-time/5)
x = carrier + noise
# Compute and plot the spectrogram.
f, t, Sxx = signal.spectrogram(x, fs)
plt.pcolormesh(t, f, Sxx, shading='gouraud')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.show()
# !
Pxx, freqs, bins, im = plt.specgram(samples, NFFT=1024, Fs=44100, noverlap=900)
# plt.yscale('log')
# plt.xscale('log')
plt.show()
print("making spectrogram...")
f, t, Sxx = signal.spectrogram(samples, sample_rate, mode='magnitude')
print(f"f:\n{f}")
print(f"t:\n{t}")
print(f"Sxx:\n{Sxx}")
print("making graph...")
# plt.pcolormesh(t, f, Sxx, shading='gouraud')
# plt.ylabel('Frequency [Hz]')
# plt.xlabel('Time [sec]')
# plt.show()
plt.pcolormesh(t, f, np.log10(Sxx), shading='gouraud')
# plt.pcolormesh(t, f, Sxx, shading='gouraud')
plt.imshow(Sxx)
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
# plt.yscale('log')
# plt.xscale('log')
plt.show()
print("exporing data...")
# data = {}
# data['f'] = f.tolist()
# data['t'] = t.tolist()
# data['Sxx'] = Sxx.tolist()
# with open('data.txt', 'w') as outfile:
# json.dump(data, outfile)