Skip to content

Update simpleio.tone to match 3.x audioio api #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 2, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions simpleio.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
* Author(s): Scott Shawcroft
"""
import time
import sys
try:
import audioio
except ImportError:
Expand All @@ -45,21 +46,34 @@ def tone(pin, frequency, duration=1, length=100):
:param int length: Variable size buffer (optional)
:param int duration: Duration of tone in seconds (optional)
"""
if length * frequency > 350000:
length = 350000 // frequency
try:
# pin with PWM
with pulseio.PWMOut(pin, frequency=int(frequency), variable_frequency=False) as pwm:
pwm.duty_cycle = 0x8000
time.sleep(duration)
except ValueError:
# pin without PWM
sample_length = length
square_wave = array.array("H", [0] * sample_length)
for i in range(sample_length / 2):
square_wave[i] = 0xFFFF
sample_tone = audioio.AudioOut(pin, square_wave)
sample_tone.frequency = int(len(square_wave) * frequency)
if not sample_tone.playing:
sample_tone.play(loop=True)
time.sleep(duration)
sample_tone.stop()
if sys.implementation.version[0] >= 3:
square_wave_sample = audioio.RawSample(square_wave)
square_wave_sample.sample_rate = int(len(square_wave) * frequency)
with audioio.AudioOut(pin) as dac:
if not dac.playing:
dac.play(square_wave_sample, loop=True)
time.sleep(duration)
dac.stop()
else:
sample_tone = audioio.AudioOut(pin, square_wave)
sample_tone.frequency = int(len(square_wave) * frequency)
if not sample_tone.playing:
sample_tone.play(loop=True)
time.sleep(duration)
sample_tone.stop()



Expand Down