-
-
Save aqzlpm11/1f958be653eb957ed068f1a70124174d to your computer and use it in GitHub Desktop.
相位差,人耳听觉实验
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Created on Mon Mar 22 23:25:50 2021 | |
@author: aqzlp | |
""" | |
#%% | |
import pyaudio | |
import numpy as np | |
import matplotlib.pyplot as plt | |
def play_sound(samples, fs, volume=1): | |
p = pyaudio.PyAudio() | |
# for paFloat32 sample values must be in range [-1.0, 1.0] | |
stream = p.open(format=pyaudio.paFloat32, | |
channels=1, | |
rate=fs, | |
output=True) | |
stream.write(volume*samples) | |
stream.stop_stream() | |
stream.close() | |
p.terminate() | |
def generate_signal(fs, f1, f2, theta1=0, theta2=0, duration=5): | |
""" | |
fade_in_out: (float) 淡入淡出时长 | |
""" | |
# generate samples, note conversion to float32 array | |
samples = (np.sin(2*np.pi*np.arange(fs*duration)*f1/fs + theta1)).astype(np.float32) | |
plt.plot(samples[:200]) | |
samples2 = (np.sin(2*np.pi*np.arange(fs*duration)*f2/fs + theta2)).astype(np.float32) | |
plt.plot(samples2[:200]) | |
samples += samples2 | |
samples = samples / np.max(np.abs(samples)) | |
# 淡入淡出 | |
start = int(fs*0.01) | |
factors = [v/start for v in range(start)] | |
samples[:start] *= factors | |
samples[-start:] *= factors[::-1] | |
plt.show() | |
return samples | |
fs = 16000 | |
f1 = 400 | |
f2 = 493 | |
samples = generate_signal(fs=fs, f1=f1, f2=f2, theta1=0, theta2=0) | |
play_sound(samples, fs=fs, volume=0.5) | |
theta = 2 * np.pi * np.random.rand() | |
samples = generate_signal(fs=fs, f1=f1, f2=f2, theta1=theta, theta2=theta) | |
play_sound(samples, fs=fs, volume=0.5) | |
theta = 2 * np.pi * np.random.rand() | |
samples = generate_signal(fs=fs, f1=f1, f2=f2, theta1=0, theta2=theta) | |
play_sound(samples, fs=fs, volume=0.5) | |
print(f"theta_delta = {theta/2/np.pi}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment