@@ -374,6 +374,11 @@ def _generate_sample(self, length=100):
374374 self ._sample = self ._audio_out (board .SPEAKER ) # pylint: disable=not-callable
375375 self ._sine_wave_sample = audiocore .RawSample (self ._sine_wave )
376376
377+ def _enable_speaker (self , enable ):
378+ if not hasattr (board , "SPEAKER_ENABLE" ):
379+ return
380+ self ._speaker_enable .value = enable
381+
377382 def play_tone (self , frequency , duration ):
378383 """ Produce a tone using the speaker. Try changing frequency to change
379384 the pitch of the tone.
@@ -394,8 +399,7 @@ def start_tone(self, frequency):
394399 :param int frequency: The frequency of the tone in Hz
395400
396401 """
397- if hasattr (board , "SPEAKER_ENABLE" ):
398- self ._speaker_enable .value = True
402+ self ._enable_speaker (enable = True )
399403 length = 100
400404 if length * frequency > 350000 :
401405 length = 350000 // frequency
@@ -413,8 +417,7 @@ def stop_tone(self):
413417 self ._sample .stop ()
414418 self ._sample .deinit ()
415419 self ._sample = None
416- if hasattr (board , "SPEAKER_ENABLE" ):
417- self ._speaker_enable .value = False
420+ self ._enable_speaker (enable = False )
418421
419422 def play_file (self , file_name ):
420423 """ Play a .wav file using the onboard speaker.
@@ -424,12 +427,10 @@ def play_file(self, file_name):
424427 """
425428 # Play a specified file.
426429 self .stop_tone ()
427- if hasattr (board , "SPEAKER_ENABLE" ):
428- self ._speaker_enable .value = True
430+ self ._enable_speaker (enable = True )
429431 with self ._audio_out (board .SPEAKER ) as audio : # pylint: disable=not-callable
430432 wavefile = audiocore .WaveFile (open (file_name , "rb" ))
431433 audio .play (wavefile )
432434 while audio .playing :
433435 pass
434- if hasattr (board , "SPEAKER_ENABLE" ):
435- self ._speaker_enable .value = False
436+ self ._enable_speaker (enable = True )
0 commit comments