Created
June 7, 2024 09:58
-
-
Save jaggzh/5e65d930b3f18aa0795cd442755d68a7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import numpy as np | |
import simpleaudio as sa | |
import threading | |
import time | |
def play_tone(freq, dur, delay): | |
# Wait for the specified delay before playing the tone | |
time.sleep(delay) | |
# Sample rate (samples per second) | |
sample_rate = 44100 | |
# Generate array with dur*sample_rate steps, ranging between 0 and dur | |
t = np.linspace(0, dur, int(dur * sample_rate), False) | |
# Generate a sine wave of frequency freq | |
note = np.sin(freq * t * 2 * np.pi) | |
# Ensure that highest value is in 16-bit range | |
audio = note * (2**15 - 1) / np.max(np.abs(note)) | |
audio = audio.astype(np.int16) | |
# Start playback | |
play_obj = sa.play_buffer(audio, 1, 2, sample_rate) | |
# Wait for playback to finish | |
play_obj.wait_done() | |
def tone(freq, dur=0.2, bg=False, delay=0): | |
if bg: | |
# Run play_tone in a background thread with the specified delay | |
thread = threading.Thread(target=play_tone, args=(freq, dur, delay)) | |
thread.start() | |
else: | |
# Play tone in the foreground with the specified delay | |
play_tone(freq, dur, delay) | |
# Example usage | |
if __name__ == "__main__": | |
tone(440, 0.5, delay=1) # Play an A4 note for 0.5 seconds after a 1-second delay in the foreground | |
tone(880, 0.5, bg=True, delay=2) # Play an A5 note for 0.5 seconds after a 2-second delay in the background |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment