def __init__(self): self.root = None self.keycode = 0 self.modifiers = 0 self.activated = False self.observer = None self.acquire_key = 0 self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE self.tkProcessKeyEvent_old = None if getattr(sys, 'frozen', False): respath = normpath( join(dirname(sys.executable), os.pardir, 'Resources')) elif __file__: respath = dirname(__file__) else: respath = '.' self.snd_good = NSSound.alloc( ).initWithContentsOfFile_byReference_( join(respath, 'snd_good.wav'), False) self.snd_bad = NSSound.alloc().initWithContentsOfFile_byReference_( join(respath, 'snd_bad.wav'), False)
def loud(self): self.snd_warn = NSSound.alloc( ).initWithContentsOfFile_byReference_( utils2to3.abspathmaker(__file__, 'sounds', 'snd_warn.wav'), False) self.snd_notify = NSSound.alloc( ).initWithContentsOfFile_byReference_( utils2to3.abspathmaker(__file__, 'sounds', 'snd_notify.wav'), False)
def executeCapture(self): self.photoView.setHidden_(False) self.captureView.setHidden_(True) self.previewButton.setHidden_(False) self.countdownCheckbox.setHidden_(True) self.captureButton.setHidden_(True) self.useButton.setEnabled_(True) if self.captureSession is not None: self.captureImage() NSSound.soundNamed_("Grab").play() self.captureSession.stopRunning()
def __init__(self): self.pSound = [True] for x in range(1,5): self.pSound.append(NSSound.alloc()) print "Loading Player %d sound." %(x,) self.pSound[x].initWithContentsOfFile_byReference_("%s/p%d.mp3" % (sound_path, x), True) print "Loading Error and Timeout sounds" self.pSoundError = NSSound.alloc() self.pSoundError.initWithContentsOfFile_byReference_("%s/erro.mp3" % (sound_path,), True) self.pSoundTimeOut = NSSound.alloc() self.pSoundTimeOut.initWithContentsOfFile_byReference_("%s/timeout.mp3" % (sound_path,), True)
def executeTimerCapture_(self, timer): if self.countdown_counter == 1: self.executeCapture() self.countdownProgress.stopAnimation_(None) self.countdownCheckbox.setHidden_(True) self.countdownProgress.setHidden_(True) self.timer.invalidate() self.timer = None else: self.countdown_counter = self.countdown_counter - 1 NSSound.soundNamed_("Tink").play() self.countdownProgress.setDoubleValue_(self.countdown_counter)
def executeTimerCapture_(self, timer): if self.countdown_counter == 1: self.executeCapture() self.countdownProgress.stopAnimation_(None) self.countdownCheckbox.setHidden_(True) self.mirrorButton.setHidden_(True) self.countdownProgress.setHidden_(True) self.timer.invalidate() self.timer = None else: self.countdown_counter = self.countdown_counter - 1 NSSound.soundNamed_("Tink").play() self.countdownProgress.setDoubleValue_(self.countdown_counter)
def __init__(self): self.root = None self.keycode = 0 self.modifiers = 0 self.activated = False self.observer = None self.acquire_key = 0 self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE self.tkProcessKeyEvent_old = None self.snd_good = NSSound.alloc().initWithContentsOfFile_byReference_(join(config.respath, 'snd_good.wav'), False) self.snd_bad = NSSound.alloc().initWithContentsOfFile_byReference_(join(config.respath, 'snd_bad.wav'), False)
def _play_sound(cls, file, playing_time=None): """ Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. """ from AppKit import NSSound from Foundation import NSURL if '://' not in file: if not file.startswith('/'): from os import getcwd file = f'{getcwd()}/{file}' file = f'file://{file}' nssound = NSSound.alloc().initWithContentsOfURL_byReference_(NSURL.URLWithString_(file), True) if not nssound: raise IOError(f'Unable to load sound named: {file}') nssound.play() if playing_time is None: time.sleep(nssound.duration()) else: time.sleep(playing_time)
def play_sound_file(path_to_soundfile): path_to_soundfile = check_soundfile_path(path_to_soundfile) if path_to_soundfile is None: return path_to_soundfile = str(path_to_soundfile) if sys.platform == 'win32': import winsound try: winsound.PlaySound(path_to_soundfile, winsound.SND_FILENAME|winsound.SND_ASYNC) except Exception: log.exception('Sound Playback Error') elif sys.platform == 'darwin': try: from AppKit import NSSound except ImportError: log.exception('Sound Playback Error') return sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_(path_to_soundfile, True) sound.play() elif app.is_installed('GSOUND'): try: app.gsound_ctx.play_simple({'media.filename' : path_to_soundfile}) except GLib.Error as error: log.error('Could not play sound: %s', error.message)
def _playsoundOSX(sound, block=True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. ''' from AppKit import NSSound from Foundation import NSURL from time import sleep if '://' not in sound: if not sound.startswith('/'): from os import getcwd sound = getcwd() + '/' + sound sound = 'file://' + sound url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError('Unable to load sound named: ' + sound) nssound.play() if block: sleep(nssound.duration())
def mac_play(path): """ play a sound using mac api """ macsound = NSSound.alloc() macsound.initWithContentsOfFile_byReference_(path, True) macsound.play()
def mac_play(self, path): """ play a sound using mac api """ macsound = NSSound.alloc() macsound.initWithContentsOfFile_byReference_(path, True) macsound.play()
def play(self, fp): from AppKit import NSSound sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_(fp.name, True) sound.play() while sound.isPlaying(): time.sleep(1)
def playSound(): import nuke import os import nukescripts macSound = 'PATH/TO/SOUND/FILE' winSound = os.path.dirname( nuke.env['ExecutablePath']) + '/' + 'plugins/user/user/Beep.WAV' if nuke.env["MACOS"]: sys.path.append( '/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python' ) sys.path.append( '/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjC' ) from AppKit import NSSound sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_(macSound, True) sound.play() elif nuke.env["WIN32"]: import winsound winsound.PlaySound(winSound, winsound.SND_FILENAME | winsound.SND_ASYNC) # TopDir = os.path.dirname(nuke.env['ExecutablePath']) + '/'; # if nuke.env['MACOS']: # TopDir = os.path.abspath(TopDir + '../../../') + '/' #nukescripts.start(TopDir + 'plugins/user/user/Beep.WAV')
def _playsoundOSX(sound, block = True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. ''' from AppKit import NSSound from Foundation import NSURL from time import sleep if '://' not in sound: if not sound.startswith('/'): from os import getcwd sound = getcwd() + '/' + sound sound = 'file://' + sound url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError('Unable to load sound named: ' + sound) nssound.play() if block: sleep(nssound.duration())
def play(self, sound_theme, sound): if self.beep and not self.isMac: gtk.gdk.beep() return for theme in (sound_theme, 'default'): soundPath = os.path.join(paths.SOUNDS_PATH, sound_theme, sound + ".wav") if os.path.exists(soundPath): break else: soundPath = '' if not soundPath: return if os.name == "nt": winsound.PlaySound(soundPath, winsound.SND_FILENAME | winsound.SND_ASYNC) elif os.name == "posix": if self.canGstreamer: loc = "file://" + soundPath self.player.set_property('uri', loc) self.player.set_state(gst.STATE_PLAYING) elif self.isMac: macsound = NSSound.alloc() macsound.initWithContentsOfFile_byReference_( \ soundPath, True) macsound.play() while macsound.isPlaying(): pass else: os.popen4(self.command + " " + soundPath)
def _playsoundOSX(sound, block=True): from AppKit import NSSound from time import sleep sound = NSSound.alloc().initWithContentsOfFile_byReference_(sound, True) sound.play() if block: sleep(sound.duration())
def __init__(self): self.root = None self.keycode = 0 self.modifiers = 0 self.activated = False self.observer = None self.acquire_key = 0 self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE self.tkProcessKeyEvent_old = None self.snd_good = NSSound.alloc( ).initWithContentsOfFile_byReference_( join(config.respath, 'snd_good.wav'), False) self.snd_bad = NSSound.alloc().initWithContentsOfFile_byReference_( join(config.respath, 'snd_bad.wav'), False)
def loadSounds(self): self._sounds = {} directory = self.getSoundDirectory() if directory and os.path.exists(directory): for fileName in os.listdir(directory): path = os.path.join(directory, fileName) sound = NSSound.alloc().initWithContentsOfFile_byReference_( path, False) if sound is not None: self._sounds[fileName] = sound
def do_play(self): if self.playing or not self.queue: return self.playing = True sample = self.queue[0] del self.queue[0] self.impl = NSSound.alloc() data = NSData.alloc().initWithBytes_length_(sample, len(sample)) self.impl.initWithData_(data) self.impl.setDelegate_(self) self.impl.play()
def _playsoundOSX(sound): from AppKit import NSSound from Foundation import NSURL from time import sleep url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError("Unable to load sound named: " + sound) nssound.play()
def play_sound(sound_file): """Plays the audio file that is at the fully qualified path `sound_file`""" system = platform.system() if system == "Windows": import winsound winsound.PlaySound(sound_file, winsound.SND_FILENAME | winsound.SND_ASYNC) elif system == "Darwin": # macOS from AppKit import NSSound from Foundation import NSURL cwd = os.getcwd() url = NSURL.URLWithString_("file://" + sound_file) NSSound.alloc().initWithContentsOfURL_byReference_(url, True).play() else: # Linux import subprocess command = ["aplay", sound_file] subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, universal_newlines=True)
def __init__(self): self.root = None self.keycode = 0 self.modifiers = 0 self.activated = False self.observer = None self.acquire_key = 0 self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE self.tkProcessKeyEvent_old = None if getattr(sys, 'frozen', False): respath = normpath(join(dirname(sys.executable), os.pardir, 'Resources')) elif __file__: respath = dirname(__file__) else: respath = '.' self.snd_good = NSSound.alloc().initWithContentsOfFile_byReference_(join(respath, 'snd_good.wav'), False) self.snd_bad = NSSound.alloc().initWithContentsOfFile_byReference_(join(respath, 'snd_bad.wav'), False)
def __init__(self, sound): self.sound = sound if '://' not in self.sound: if not self.sound.startswith('/'): from os import getcwd self.sound = getcwd() + '/' + self.sound self.sound = 'file://' + self.sound url = NSURL.URLWithString_(self.sound) self.nssound = NSSound.alloc().initWithContentsOfURL_byReference_( url, True) if not self.nssound: raise IOError('Unable to load sound named: ' + self.sound)
def play_sound_darwin(self, wav_file_as_byte_array): from AppKit import NSSound from AppKit import NSObject from AppKit import NSData nssound = NSSound.alloc() data = NSData.alloc().initWithBytes_length_(wav_file_as_byte_array, len(wav_file_as_byte_array)) nssound.initWithData_(data) nssound.setDelegate_(self) if (not nssound): raise IOError('Unable to load sound.') nssound.play()
def _playsoundOSX(sound): from AppKit import NSSound from Foundation import NSURL if '://' not in sound: if not sound.startswith('/'): sound = os.getcwd() + '/' + sound sound = 'file://' + sound url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError('Unable to load sound named: ' + sound) nssound.play()
def generate(self, text, host="", name="Morse" ): tmpdir = mkdtemp() try: filename = os.path.join(tmpdir, "objc.wav") fd = open(filename, 'wb') self.bytesForStr( text ).tofile(fd) fd.close() player = NSSound.alloc() try: player.initWithContentsOfFile_byReference_(filename, False) player.play() sleep(player.duration() + 1) finally: del player finally: rmtree(tmpdir)
def play_path(self, soundPath): if os.name == "nt": winsound.PlaySound(soundPath, winsound.SND_FILENAME | winsound.SND_ASYNC) elif os.name == "posix": if self.canGstreamer: loc = "file://" + soundPath self.player.set_property('uri', loc) self.player.set_state(gst.STATE_PLAYING) elif self.isMac: macsound = NSSound.alloc() macsound.initWithContentsOfFile_byReference_( \ soundPath, True) macsound.play() while macsound.isPlaying(): pass else: os.popen4(self.command + " " + soundPath)
def play_path(self, soundPath): if os.name == "nt": winsound.PlaySound(soundPath, winsound.SND_FILENAME | winsound.SND_ASYNC) elif os.name == "posix": if self.canGstreamer: loc = "file://" + soundPath self.player.set_property('uri', loc) self.player.set_state(gst.STATE_PLAYING) elif self.isMac: macsound = NSSound.alloc() macsound.initWithContentsOfFile_byReference_( \ soundPath, True) macsound.play() while macsound.isPlaying(): pass else: # os.popen4(self.command + " " + soundPath) subprocess.Popen([self.command, soundPath])
def _playaudioOSX(sound, block=True): ''' Utilizes AppKit.NSSound. ''' from AppKit import NSSound from Foundation import NSURL from time import sleep if '://' not in sound: if not sound.startswith('/'): from os import getcwd sound = getcwd() + '/' + sound sound = 'file://' + sound url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError('Unable to load sound named: ' + sound) nssound.play() if block: sleep(nssound.duration())
def present(self): """Present the Alert, giving up after configured time.. Returns: Int result code, based on PyObjC enums. See NSAlert Class reference, but result should be one of: User clicked the cancel button: NSAlertFirstButtonReturn = 1000 Alert timed out: NSRunAbortedResponse = -1001 """ if self.timer: NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode) # Start a Cocoa application by getting the shared app object. # Make the python app the active app so alert is noticed. app = NSApplication.sharedApplication() app.activateIgnoringOtherApps_(True) if self.alert_sound: sound = NSSound.soundNamed_(self.alert_sound).play() result = self.runModal() # pylint: disable=no-member print result return result
def main(): # Play a sound snd = "paper_shredder.wav" sound = NSSound.alloc() #sound.initWithContentsOfFile_byReference_('/Users/aleray/Desktop/Paper Shredder.app/Contents/Resources/paper_shredder.wav', True) sound.play() meter = EasyDialogs.ProgressBar('Compressing your images...', maxval=100, label='Starting', ) for i in xrange(1, 101): phase = '%d %% Completed' % i print phase meter.label(phase) meter.inc() time.sleep(0.01) print 'Done with loop' time.sleep(1) del meter print 'The dialog should be gone now' for infile in sys.argv[1:]: fileName = os.path.basename(sys.argv[1]).split(".")[0] fileExt = os.path.basename(sys.argv[1]).split(".")[1] outfile = "/Users/aleray/Recycled/Image Compression 1/%s.compressed.%s" % (fileName, fileExt) if infile != outfile: try: im = Image.open(infile) xsize, ysize = im.size ysize = ysize/20 im = im.resize([xsize, ysize]) print im.size im.save(outfile, "JPEG") im.show() except IOError: print "cannot create thumbnail for", infile
def _playsoundOSX(sound, block = True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. ''' try: from AppKit import NSSound except ImportError: logger.warning("playsound could not find a copy of AppKit - falling back to using macOS's system copy.") sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC') from AppKit import NSSound from Foundation import NSURL from time import sleep sound = _handlePathOSX(sound) url = NSURL.URLWithString_(sound) if not url: raise PlaysoundException('Cannot find a sound with filename: ' + sound) for i in range(5): nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if nssound: break else: logger.debug('Failed to load sound, although url was good... ' + sound) else: raise PlaysoundException('Could not load sound with filename, although URL was good... ' + sound) nssound.play() if block: sleep(nssound.duration())
def present(self): """Present the Alert, giving up after configured time.. Returns: Int result code, based on PyObjC enums. See NSAlert Class reference, but result should be one of: User clicked the cancel button: NSAlertFirstButtonReturn = 1000 Alert timed out: NSRunAbortedResponse = -1001 """ if self.timer: NSRunLoop.currentRunLoop().addTimer_forMode_( self.timer, NSModalPanelRunLoopMode) # Start a Cocoa application by getting the shared app object. # Make the python app the active app so alert is noticed. app = NSApplication.sharedApplication() app.activateIgnoringOtherApps_(True) if self.alert_sound: sound = NSSound.soundNamed_(self.alert_sound).play() result = self.runModal() # pylint: disable=no-member print result return result
def second_time_crate(): global end_time2 its_time = False while its_time == False: its_time = False # ------------------------------------------ # # ------ Local Time in your country! ------- # # ------------------------------------------ # Timer = time.asctime(time.localtime(time.time())) # ------------------------- # # ------ Timer Loop ------- # # ------------------------- # if Timer == end_time2: its_time = True print("It's time to take your puppy out!") # ----------------------------- # # ------ Prepare Sounds ------- # # ----------------------------- # sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_( '/Library/Audio/Apple Loops/Apple/01 Hip Hop/Afloat Beat.caf', True) sound.play() # --------------------------------------------------------------------------------------------- # # ------ Add 20 seconds time sleep (time the song play) before to jump to the next part ------- # # --------------------------------------------------------------------------------------------- # time.sleep(20) third_time_crate() # --------------------------------------------- # # ------ Print this until the time out! ------- # # --------------------------------------------- # else: print("Local current time :", Timer) print("\tTimer end at: ", end_time2) print("." * 50) time.sleep(1) its_time = False
def __init__(self, file): self._sound = NSSound.alloc() self._sound.initWithContentsOfFile_byReference_(file, True)
def load_sound(name, loop=False): f = os.path.join(basedir, 'sounds', name + '.wav') sounds[name] = NSSound.alloc() sounds[name].initWithContentsOfFile_byReference_(f, True) if loop: sounds[name].setLoops_(True)
def __init__(self, path): self.sound = NSSound.alloc() self.sound.initWithContentsOfFile_byReference_(path, True)
def _load_player(self): return NSSound.alloc().initWithContentsOfFile_byReference_( self._filename, True)
def start_record(self): if self.object1.poorSignal!=0: print 'signal is poor' self.text.insert(INSERT, 'bad signal\n') else: delta = [] midgamma = [] lowgamma = [] theta = [] highalpha = [] lowalpha = [] highbeta = [] lowbeta = [] self.text.insert(INSERT,'\n\n') self.text.insert(INSERT, 'progress:'+str(self.progress)+':\n') self.text.insert(INSERT, 'question:'+str(self.audio_seq[self.progress])+':\n') self.text.see(END) print str(self.audio_seq[self.progress]) sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_(str(self.audio_seq[self.progress])+'.mp3', True) sound.play() for i in range(0,RECORD_TIME): if self.object1.poorSignal!=0: print "because signal("+str(self.object1.poorSignal)+") is bad, we skip this round." break else: delta.append(self.object1.delta) midgamma.append(self.object1.midGamma) lowgamma.append(self.object1.lowGamma) theta.append(self.object1.theta) highalpha.append(self.object1.highAlpha) lowalpha.append(self.object1.lowAlpha) highbeta.append(self.object1.highBeta) lowbeta.append(self.object1.lowBeta) print 'delta:'+str(self.object1.delta) print 'theta:'+str(self.object1.theta) print 'highalpha:'+str(self.object1.highAlpha) print 'midgamma:'+str(self.object1.midGamma) print 'recording' print self.object1.poorSignal time.sleep(1) if len(delta)==RECORD_TIME: #print "std(delta)="+str(int(np.std(np.array(delta)))) #print "std(midgamma)="+str(int(np.std(np.array(midgamma)))) #print "std(lowgamma)="+str(int(np.std(np.array(lowgamma)))) #print "std(theta)="+str(int(np.std(np.array(theta)))) self.row_data.append(delta) self.row_data.append(theta) self.row_data.append(lowalpha) self.row_data.append(highalpha) self.row_data.append(lowbeta) self.row_data.append(highbeta) self.row_data.append(lowgamma) self.row_data.append(midgamma) print self.row_data self.easy_btn['state']='normal' self.hard_btn['state']='normal' self.sta_btn['state'] = 'disabled' #for i in range(0,5): # self.row_data.append(int(np.std(np.array(delta[0:RECORD_TIME-i])))) # self.row_data.append(int(np.std(np.array(midgamma[0:RECORD_TIME-i])))) # self.row_data.append(int(np.std(np.array(lowgamma[0:RECORD_TIME-i])))) # self.row_data.append(int(np.std(np.array(theta[0:RECORD_TIME-i])))) sound.stop()
def play(self): self.ns_sound = NSSound.alloc() self.ns_sound.initWithContentsOfFile_byReference_(self.path, True) self.ns_sound.play()
#!/usr/bin/env python ## MacOS ѕpecific # plays an mp3 file from AppKit import NSSound sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_("/Users/wishi/test.mp3", True) sound.play()
chr(0), chr(0), chr(0), chr(0), chr(0), chr(0) ] for t in o: b += t o = chr(0) * 5512 for n in s: t = '' g = .125 * h**n for y in range(2756): v = int(2e4 * sin(g * y)) t += chr((v & 0xff00) >> 8) + chr(v & 0xff) b += t b += o aifff = open('1kintro_macosx.aiff', 'wb') aifff.write(b) aifff.close() sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_("1kintro_macosx.aiff", True) try: sound.setLoops_(True) sound.play() except AttributeError: Thread(target=k).start() z = time() glutMainLoop()
def main(): # Play a sound snd = "paper_shredder.wav" #os.system("/Users/aleray//bin/mplayer %s < /dev/tty1 >| ~/error.log" % snd) #os.system("/Users/aleray/bin/mplayer %s >| ~/error.log" % snd) #os.system("/Applications/VLC.app/Contents/MacOS/VLC -I ncurses %s &" % snd) sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_('/Users/aleray/Desktop/Paper Shredder.app/Contents/Resources/paper_shredder.wav', True) sound.play() meter = EasyDialogs.ProgressBar('Shredding your file...', maxval=100, label='Starting', ) for i in xrange(1, 101): phase = '%d %% Completed' % i print phase meter.label(phase) meter.inc() time.sleep(0.01) print 'Done with loop' time.sleep(1) del meter print 'The dialog should be gone now' # Nombre de caractères par ligne du fichier original, Nombre de caractère pas ligne des fichiers générés nc = 40 nf = 5 # Récupère le premier argument et le formate f = open(sys.argv[1],'r') g = f.read() f.close() g = wrap(g,nc) # À revoir car supprime n'importe quel type de fichier cmd = "rm %s" % sys.argv[1] os.system(cmd) # Récupère le chemin relatif de l'argument sans son extension basePath = os.path.splitext(sys.argv[1])[0] fileName = os.path.basename(sys.argv[1]).split(".")[0] fileExt = os.path.basename(sys.argv[1]).split(".")[1] destinationPath = "/Users/aleray/Recycled/Paper Shredder/" # liste des fichiers généré createdDocs = [] # Découpe ligne par ligne le fichier original et cré des "bandes" for i in range(nc/nf): newContent="" for line in g.split("\n"): newContent += line[i*nf:(i*nf)+nf]+"\n" newPath = '%s%s_%s.%s' % (destinationPath, fileName, i, fileExt) createdDocs.append(newPath) newFile = open(newPath, 'w') newFile.write(newContent) te = app('TextEdit') te.activate() for i in range(len(createdDocs)): te.open(Alias(createdDocs[i])) te.windows[0].bounds.set([100+35*i, 100, 200+35*i, 800]) # fait une petite pause avant de tout refermer time.sleep(2) for window in te.windows.get()[::-1]: window.close()
def Alarm(): global list end_time1 = input("At what time do you want an alarm?\n(Format 24h: hh:mm:ss)\n>>") reminder = input("What's the reminder for?\n>>") # --------------------------------------------- # # -- Append your reminder in list = [] above -- # # --------------------------------------------- # all = "Time: " + end_time1 + " Your Reminder is: " + reminder list.append(all) # ---------------------------------------------------------------------------- # # -- Here you append your history to the history file: history_reminder.txt -- # # ---------------------------------------------------------------------------- # with open("history_reminder.txt", 'a') as output: output.write(all + '\n') Last_reminder = input("Do you want to see your all reminder schedules?\n[yes/no]\n>>") if 'yes' in Last_reminder: print(list) question = input("Are you done?") if 'yes' in question: pass else: pass its_time = False while its_time == False: its_time = False # ------------------------------------------ # # ------ Local Time in your country! ------- # # ------------------------------------------ # clock = time.localtime() # get struct_time Timer = time.strftime("%a, %b %d %Y, %X%p (%Z)", clock) # ------------------------- # # ------ Timer Loop ------- # # ------------------------- # if end_time1 in Timer: its_time = True print("Your Reminder is:\n(",reminder,")") pyttsx3.speak(reminder) # < ----------------------------------------- Here the script play your reminder text # ----------------------------- # # ------ Prepare Sounds ------- # # ----------------------------- # # --------------------------------------------- # # I couldn't make this part work with Linux so # # just delect this part if you are under linux # # --------------------------------------------- # sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_( 'reminder_voice.mp3', True) # < ------------------------- Here should be your own song. sound.play() # ----------------------------------------------------------------------------------------------------- # # ------ Add 8 seconds time sleep (time the song play for me, you can add more or less for you) ------- # # ----------------------------------------------------------------------------------------------------- # time.sleep(8) while sound.isPlaying(): # < ------------------------------------- Delect this as well if you are under Linux another = input("Do you want an other one?\n[yes/no]\n>>") # < ----- Reposition this part is you delect the sound player above if another == 'yes': return Alarm() else: # -------------------------------------------- # # -- Here you print the history of your day -- # # -------------------------------------------- # print(list) break # --------------------------------------------- # # ------ Print this until the time out! ------- # # --------------------------------------------- # else: start = time.strftime("%X") format = '%H:%M:%S' time_left = datetime.strptime(end_time1, format) - datetime.strptime(start, format) # Subtract the time left before end time. print("Local current time :", Timer) print("\tTimer end at: ", end_time1) print("\tYour reminder is:", reminder) print("\tTime left: ", time_left) print("." * 50) time.sleep(1) os.system('clear') its_time = False
def executeCapture(self): self.captureView.getSnapshot() NSSound.soundNamed_("Grab").play()
def start_record(self): if self.progress == 30: print 'No more question' return 0 if self.object1.poorSignal!=0: print 'signal is poor:'+str(self.object1.poorSignal) self.text.insert(INSERT, 'bad signal\n') self.sta_btn['state'] = 'normal' else: delta = [] midgamma = [] lowgamma = [] theta = [] highalpha = [] lowalpha = [] highbeta = [] lowbeta = [] self.text.insert(INSERT,'\n\n') self.text.insert(INSERT, 'progress:'+str(self.progress)+':\n') self.text.insert(INSERT, 'question:'+str(self.audio_seq[self.progress])+':\n') self.text.see(END) print str(self.audio_seq[self.progress]) sound = NSSound.alloc() sound.initWithContentsOfFile_byReference_(str(doc_id)+'-'+str(self.audio_seq[self.progress])+'.mp3', True) sound.play() for i in range(0,RECORD_TIME): if self.object1.poorSignal!=0: print "because signal("+str(self.object1.poorSignal)+") is bad, we skip this round." break else: delta.append(self.object1.delta) midgamma.append(self.object1.midGamma) lowgamma.append(self.object1.lowGamma) theta.append(self.object1.theta) highalpha.append(self.object1.highAlpha) lowalpha.append(self.object1.lowAlpha) highbeta.append(self.object1.highBeta) lowbeta.append(self.object1.lowBeta) print 'delta:'+str(self.object1.delta) print 'theta:'+str(self.object1.theta) print 'highalpha:'+str(self.object1.highAlpha) print 'midgamma:'+str(self.object1.midGamma) print 'recording' print self.object1.poorSignal time.sleep(1) sound.stop() if len(delta)==RECORD_TIME: self.row_data.append(delta) self.row_data.append(theta) self.row_data.append(lowalpha) self.row_data.append(highalpha) self.row_data.append(lowbeta) self.row_data.append(highbeta) self.row_data.append(lowgamma) self.row_data.append(midgamma) print self.row_data self.sta_btn['state'] = 'disabled' self.difficulty() else: self.start_record()
def __init__(self, soundFile): self.sound = NSSound.alloc() try: self.sound.initWithContentsOfFile_byReference_(soundFile, True) except: print 'Error opening sound file: ' + soundFile
def __init__(self): self.snd_warn = NSSound.alloc().initWithContentsOfFile_byReference_(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'sounds/snd_warn.wav'), False) self.snd_notify = NSSound.alloc().initWithContentsOfFile_byReference_(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'sounds/snd_notify.wav'), False)