Playing audio

To begin with, we have added 24 sound samples in .wav format in a folder named sounds in this chapter's code folder. These audio files correspond to the 24 notes on our keyboard. The audio files are named according to the note name it represents.

In order to keep the audio processing separate from the GUI code, we create a new file called audio.py (7.03). The code is defined as follows:

import simpleaudio as sa
from _thread import start_new_thread
import time

def play_note(note_name):
wave_obj = sa.WaveObject.from_wave_file('sounds/' + note_name + '.wav')
wave_obj.play()

def play_scale(scale):
for note in scale:
play_note(note)
time.sleep(0.5)

def play_scale_in_new_thread(scale):
start_new_thread(play_scale,(scale,))

def play_chord(scale):
for note in scale:
play_note(note)

def play_chord_in_new_thread(chord):
start_new_thread(play_chord,(chord,))

The code description is as follows:

  • The play_note method follows the API provided by simpleaudio to play an audio file
  • The play_scale method takes in a list of notes and plays them sequentially, giving a time gap between each played note
  • The play_chord method takes a list of notes and plays them all together
  • The last two methods call these methods in new threads as we don't want to block the main GUI thread when playing these notes

Next, let's import this file (7.03 view.py):

from audio import play_note    

Next, modify the on_key_pressed method to play the given note:

def on_key_pressed(self, event):
play_note(event.widget.name)
self.change_image_to_pressed(event)

This concludes the iteration. If you now run the code and press any key on the keyboard, it should play the note for that key.

Next, we start with building the actual tutor. The next three sections will develop the scales, chords, and chord progression sections.  We will start by building the scales tutor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.247.181