-1

Hi I need to run my gui simultaneously with my alarm sound and stop the iterating alarm sound when i click ok button in the 2nd dialog box. To achieve this task i created 2 files which is the main file(gui using easygui) and the AudioFile class witch uses pyaudio to play and stop alarm sound.

main file:

from easygui import *
import sys
from AudioFile import *

    predictions[0] = 1

a = AudioFile("alarm.wav")

if (predictions[0] == 1):
    while 1:
            #play alarm sound
        a.play()
        msgbox("Critical Situation Detected!")


        msg ="Please choose an action?"
        title = "Critical Situation Detected!"
        choices = ["Ignore the Warning", "Contact Doctor", "Call Ambulance Service", "Call Hospital"]
        #choice = choicebox(msg, title, choices)
        choice = multchoicebox(msg, title, choices)

            #stop alarm sound
        a.close()

        # note that we convert choice to string, in case
        # the user cancelled the choice, and we got None.
        msgbox("You chose: " + str(choice), "Action is in Progress")

        msg = "Do you want to continue?"
        title = "Please Confirm"
        if ccbox(msg, title):     # show a Continue/Cancel dialog
                        pass  # user chose Continue
        else:
                        sys.exit(0)           # user chose Cancel

AudioFile:

import pyaudio
import wave
import sys

class AudioFile:
    chunk = 1024

    def __init__(self, file):
        """ Init audio stream """ 
        self.wf = wave.open(file, 'rb')
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(
            format = self.p.get_format_from_width(self.wf.getsampwidth()),
            channels = self.wf.getnchannels(),
            rate = self.wf.getframerate(),
            output = True
        )

    def play(self):
        """ Play entire file """
        data = self.wf.readframes(self.chunk)
        while data != '':
            self.stream.write(data)
            data = self.wf.readframes(self.chunk)

    def close(self):
        """ Graceful shutdown """ 
        self.stream.close()
        self.p.terminate()

# Usage example for pyaudio
#a = AudioFile("alarm.wav")
#a.play()
#a.close()

When i run this two codes using main file i wanted to run the alarm sound first and in background the gui should appear in the window and when i select the choices from the second window and i press ok it should stop the alarm sound but instead of that first my application play the alarm sound after it is over it start the gui. how should i play my alarm sound in the background of the gui and close it after i press the second ok button?

tk_
  • 16,415
  • 8
  • 80
  • 90

2 Answers2

1

Currently, when you run the AudioFile.play() method you will play the entire file before the msgbox("Critical Situation Detected!") command is executed.

The solution to this would be to run the alarm in a thread such that control remains in the while loop in your main file.

An example of what the threaded alarm might look like (minus the details) would be:

from threading import Thread,Event
from time import sleep

class AudioFile(Thread):
    def __init__(self):
        Thread.__init__(self)
        self._stop = Event()

    def run(self):
        self._stop.clear()

        # in this case we loop until the stop event is set
        while not self._stop.is_set():
            print "BEEP BEEP BEEP!"
            sleep(0.2)

    def stop(self):
        self._stop.set()

In your main code you would then replace a.play and a.close by a.start and a.stop. For example:

x = AudioFile()
x.start()
sleep(4)
x.stop()
ebarr
  • 7,704
  • 1
  • 29
  • 40
  • 1
    Nowhere. The sleep statement is there purely to provide an example code that runs and that demonstrates how the threading module allows you two run two logical threads at once. – ebarr May 23 '14 at 06:46
0

I came up with the solution based on @ebarr sample code.

main file:

 predictions[0] = 1

a = AudioFile("alarm.wav")

if (predictions[0] == 1):
    while 1:
        a.start()
        sleep(0.5)
        msgbox("Critical Situation Detected!")


        msg ="Please choose an action?"
        title = "Critical Situation Detected!"
        choices = ["Ignore the Warning", "Contact Doctor", "Call Ambulance Service", "Call Hospital"]
        #choice = choicebox(msg, title, choices)
        choice = multchoicebox(msg, title, choices)

        a.stop()

        # note that we convert choice to string, in case
        # the user cancelled the choice, and we got None.
        msgbox("You chose: " + str(choice), "Action is in Progress")

        msg = "Do you want to continue?"
        title = "Please Confirm"
        if ccbox(msg, title):     # show a Continue/Cancel dialog
                        pass  # user chose Continue
        else:
                        sys.exit(0)           # user chose Cancel

AudioFile:

import pyaudio
import wave
import sys

from threading import Thread,Event
from time import sleep

class AudioFile(Thread):
    chunk = 1024

    def __init__(self, file):
        """ Init audio stream """
        Thread.__init__(self)
        self.wf = wave.open(file, 'rb')
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(
            format = self.p.get_format_from_width(self.wf.getsampwidth()),
            channels = self.wf.getnchannels(),
            rate = self.wf.getframerate(),
            output = True
        )
        self._stop = Event()

def run(self):
    self._stop.clear()
    """ Play entire file """
    while not self._stop.is_set():
        data = self.wf.readframes(self.chunk)
        self.stream.write(data)

    def stop(self):
        """ Graceful shutdown """
        self._stop.set()
        self.stream.close()
        self.p.terminate()
tk_
  • 16,415
  • 8
  • 80
  • 90
  • Looks good. I am not familiar with `PyAudio`, but the nested while loop in the `run` method looks like it could cause you problems. I each pass of the inner while loop a tone of the alarm? – ebarr May 23 '14 at 06:58
  • @ebarr yes, i changed it accordingly now its working perfectly – tk_ May 27 '14 at 01:52