Skip to content

Commit 1420b3f

Browse files
authored
Merge pull request #36 from caternuson/iss35
Update simpleio.tone to match 3.x audioio api
2 parents 3ce587e + 8e650c3 commit 1420b3f

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

simpleio.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
* Author(s): Scott Shawcroft
2929
"""
3030
import time
31+
import sys
3132
try:
3233
import audioio
3334
except ImportError:
@@ -45,21 +46,34 @@ def tone(pin, frequency, duration=1, length=100):
4546
:param int length: Variable size buffer (optional)
4647
:param int duration: Duration of tone in seconds (optional)
4748
"""
49+
if length * frequency > 350000:
50+
length = 350000 // frequency
4851
try:
52+
# pin with PWM
4953
with pulseio.PWMOut(pin, frequency=int(frequency), variable_frequency=False) as pwm:
5054
pwm.duty_cycle = 0x8000
5155
time.sleep(duration)
5256
except ValueError:
57+
# pin without PWM
5358
sample_length = length
5459
square_wave = array.array("H", [0] * sample_length)
5560
for i in range(sample_length / 2):
5661
square_wave[i] = 0xFFFF
57-
sample_tone = audioio.AudioOut(pin, square_wave)
58-
sample_tone.frequency = int(len(square_wave) * frequency)
59-
if not sample_tone.playing:
60-
sample_tone.play(loop=True)
61-
time.sleep(duration)
62-
sample_tone.stop()
62+
if sys.implementation.version[0] >= 3:
63+
square_wave_sample = audioio.RawSample(square_wave)
64+
square_wave_sample.sample_rate = int(len(square_wave) * frequency)
65+
with audioio.AudioOut(pin) as dac:
66+
if not dac.playing:
67+
dac.play(square_wave_sample, loop=True)
68+
time.sleep(duration)
69+
dac.stop()
70+
else:
71+
sample_tone = audioio.AudioOut(pin, square_wave)
72+
sample_tone.frequency = int(len(square_wave) * frequency)
73+
if not sample_tone.playing:
74+
sample_tone.play(loop=True)
75+
time.sleep(duration)
76+
sample_tone.stop()
6377

6478

6579

0 commit comments

Comments
 (0)