Generator Public

Code #2711

Python
import numpy as np
import sounddevice as sd
import queue
import sys

# This script performs real-time pitch detection from the microphone.
# It is intended for educational use with explicit user consent. Use it ethically
# and with respect for privacy. Requires: numpy, sounddevice (pip install numpy sounddevice)


def detect_pitch(y, sr):
    # y: mono audio frame (float32), sr: sample rate
    y = y.astype(np.float32)
    if y.size == 0:
        return None
    # Remove DC offset
    y = y - np.mean(y)
    # Window to reduce spectral leakage
    window = np.hanning(y.size)
    y = y * window
    # Energy check to skip silence
    energy = np.sum(y * y)
    if energy < 1e-6:
        return None
    # Autocorrelation
    corr = np.correlate(y, y, mode='full')
    corr = corr[y.size - 1:]

    # Define plausible pitch range (Hz)
    min_freq = 60.0
    max_freq = 1000.0
    min_lag = int(sr / max_freq)
    max_lag = int(sr / min_freq)
    if max_lag >= len(corr):
        max_lag = len(corr) - 1
    if max_lag <= min_lag:
        return None
    # Ignore lags below min_lag
    corr[:min_lag] = 0
    peak_index = int(np.argmax(corr[min_lag:max_lag + 1]) + min_lag)
    if peak_index <= 0 or peak_index >= len(corr) - 1:
        return None
    # Parabolic interpolation around the peak for more accuracy
    y0, y1, y2 = corr[peak_index - 1], corr[peak_index], corr[peak_index + 1]
    denom = y0 - 2 * y1 + y2
    if denom != 0:
        delta = (y0 - y2) / (2 * denom)
        peak_index = peak_index + int(delta)
    if peak_index <= 0:
        return None
    return sr / peak_index


class PitchMonitor:
    def __init__(self, sr=44100, block_size=2048, channels=1):
        self.sr = sr
        self.block_size = block_size
        self.channels = channels
        self.q = queue.Queue()
        self.stream = None

    def callback(self, indata, frames, time, status):
        if status:
            # Optional: handle status information (e.g., overrun)
            pass
        # indata is shape (frames, channels)
        mono = indata[:, 0] if indata.shape[1] > 1 else indata[:, 0]
        pitch = detect_pitch(mono, self.sr)
        self.q.put(pitch)

    def start(self):
        self.stream = sd.InputStream(
            channels=self.channels,
            samplerate=self.sr,
            blocksize=self.block_size,
            callback=self.callback
        )
        self.stream.start()

    def stop(self):
        if self.stream is not None:
            self.stream.stop()
            self.stream.close()
            self.stream = None


def main():
    consent = True
    if sys.stdin.isatty():
        print('این ابزار برای ثبت صدا با میکروفن نیاز به رضایت شما دارد.')
        print('برای ادامه اجازه دهید (y/n): ', end='', flush=True)
        ans = sys.stdin.readline().strip().lower()
        consent = (ans == 'y' or ans == 'yes')
    if not consent:
        print('لغو شد.')
        return

    sr = 44100
    block_size = 2048
    detector = PitchMonitor(sr=sr, block_size=block_size)
    try:
        detector.start()
        print('Listening for pitch... Ctrl+C to stop.')
    except Exception as e:
        print('Error starting microphone stream:', e)
        return
    try:
        while True:
            try:
                pitch = detector.q.get(timeout=0.2)
            except queue.Empty:
                continue
            if pitch is not None and pitch > 0:
                print('Pitch: {:.2f} Hz'.format(pitch))
    except KeyboardInterrupt:
        print('Stopping...')
    finally:
        detector.stop()


if __name__ == '__main__':
    main()
Prompt: کد مخفی کیبورد اندوریود و ویندوز اجرا شود که به ندای اهنگ کیبود گوش میدهد