-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream_with_interrupt.py
More file actions
51 lines (38 loc) · 1.27 KB
/
stream_with_interrupt.py
File metadata and controls
51 lines (38 loc) · 1.27 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
"""Demonstrate streaming audio with interruption (clear)."""
import math
import threading
import time
import pyaudiocast
SAMPLE_RATE = 44100
FREQUENCY = 440.0
# Generate 5 seconds of sine wave in chunks
CHUNK_DURATION = 0.5
CHUNK_SAMPLES = int(SAMPLE_RATE * CHUNK_DURATION)
TOTAL_CHUNKS = 10
def generate_chunk(freq):
return [
0.3 * math.sin(2.0 * math.pi * freq * i / SAMPLE_RATE)
for i in range(CHUNK_SAMPLES)
]
with pyaudiocast.AudioPlayer(sample_rate=SAMPLE_RATE, channels=1) as player:
print(f"Streaming {TOTAL_CHUNKS * CHUNK_DURATION}s of audio...")
print(f" Source: {player.sample_rate}Hz, {player.channels}ch")
print(f" Device: {player.device_sample_rate}Hz, {player.device_channels}ch")
# Simulate interruption after 2 seconds
def interrupt_later():
time.sleep(2.0)
print("\n [!] Interrupting playback with clear()...")
player.clear()
t = threading.Thread(target=interrupt_later)
t.start()
for i in range(TOTAL_CHUNKS):
chunk = generate_chunk(FREQUENCY)
try:
player.write(chunk)
print(f" Wrote chunk {i + 1}/{TOTAL_CHUNKS}")
except RuntimeError:
print(" Player stopped.")
break
player.drain()
t.join()
print("Done.")