Python allows you to play music at regular intervals with an alarm clock and python to play music.

Source: Internet
Author: User

Python allows you to play music at regular intervals with an alarm clock and python to play music.

You can only play audio in wav format for your reference. The specific content is as follows:

Python code:

Import time import sys soundFile = 'sound.wav 'not_executed = 1 def soundStart (): if sys. platform [: 5] = 'linux ': import OS. popen2 ('aplay-Q' + soundFile) else: import winsound. playSound (soundFile, winsound. SND_FILENAME) while (not_executed): dt = list (time. localtime () hour = dt [3] minute = dt [4] if hour = 17 and minute = 38: # prompt soundStart () not_executed = 0 at 05:33 P.M.

The winsound module provides access to basic sound playing devices provided by the Windows platform. It contains functions and several constants.

Beep (frequency, duration)
Beep PC horn. The frequency parameter specifies the sound frequency in Hz and must be between 37 and 32,767.
. The duration parameter specifies the number of milliseconds the sound should last. If the system cannot beep, The RuntimeError is suspended. Note: in Windows 95 and 98, the Windows Beep () function exists but is invalid (it ignores its parameters ). In this case, Python simulates it through direct port operations (added in 2.1 ). I don't know if it works on all systems. New features in version 1.6.

PlaySound (sound, flags)
Call the PlaySound () function from the platform API. The sound parameter must be a file name, audio data as a string, or None. Its interpretation depends on the value of flags, which can be a single-digit method or a combination of the variables described below. If the system displays an error, the RuntimeError is suspended.

MessageBeep ([type = MB_ OK])
Call the MessageBeep () function from the platform API. Play a sound specified in the registry. The type parameter specifies which sound to play. The possible values are-1, MB_ICONASTERISK, MB_ICONEXCLAMATION, MB_ICONHAND, MB_ICONQUESTION, and MB_ OK. All the descriptions are as follows. Value-1 generates a ''simple beeps ''; in other words, this is a backup plan if the sound cannot be played. New features in Version 2.3.

SND_FILENAME
The sound parameter is the name of a WAV file. Do not use SND_ALIAS.

SND_ALIAS
The sound parameter is the name of a sound combination in the registry. If the registry does not contain such a name, the default sound of the playing system is also specified Unless SND_NODEFAULT. If no default sound is registered, the RuntimeError is suspended. SND_FILENAME is not used.
All Win32 systems support at least the following, and most systems support more:
Control Panel sound name corresponding to PlaySound () Name
'Systemasterisk' Asterisk
'Systemexclamation' Exclamation
'Systemdelete' Exit Windows
'Systemhand' Critical Stop
'Systemquestion 'Question

Example:

import winsound  # Play Windows exit sound. winsound.PlaySound("SystemExit", winsound.SND_ALIAS)  # Probably play Windows default sound, if any is registered (because # "*" probably isn't the registered name of any sound). winsound.PlaySound("*", winsound.SND_ALIAS) 

SND_LOOP
Play the sound repeatedly. The SND_ASYNC identifier must also be used to avoid congestion. SND_MEMORY cannot be used.

SND_MEMORY
The sound parameter provided to PlaySound () is a memory image of a WAV file (memory image) as a string.
Note: This module does not support asynchronous playback from the memory image. Therefore, the combination of this identifier and SND_ASYNC will suspend RuntimeError.

SND_PURGE
Stops Playing all instances of the specified sound.

SND_ASYNC
Return immediately. asynchronous sound playback is allowed.

SND_NODEFAULT
However, the specified sound is not found and the default sound is not played.

SND_NOSTOP
The current playback sound is not interrupted.

SND_NOWAIT
If the voice driver is busy, return immediately.

MB_ICONASTERISK
Play the SystemDefault sound.

MB_ICONEXCLAMATION
Play the SystemExclamation sound.

MB_ICONHAND
Play the SystemHand sound.

MB_ICONQUESTION
Play the SystemQuestion sound.

MB_ OK
Play the SystemDefault sound.

Instance 1

import wx from wx.lib.filebrowsebutton import FileBrowseButton  class MyFrame(wx.Frame):  def __init__(self):   wx.Frame.__init__(self, None, title="wx.Sound",size=(500,100))   p = wx.Panel(self)    self.fbb = FileBrowseButton(p,labelText="Select WAV file:",fileMask="*.wav")   btn = wx.Button(p, -1, "Play")   self.Bind(wx.EVT_BUTTON, self.OnPlaySound, btn)      sizer = wx.BoxSizer(wx.HORIZONTAL)   sizer.Add(self.fbb, 1, wx.ALIGN_CENTER_VERTICAL)   sizer.Add(btn, 0, wx.ALIGN_CENTER_VERTICAL)   border = wx.BoxSizer(wx.VERTICAL)   border.Add(sizer, 0, wx.EXPAND|wx.ALL, 15)   p.SetSizer(border)    def OnPlaySound(self, evt):   filename = self.fbb.GetValue()   self.sound = wx.Sound(filename)   if self.sound.IsOk():    self.sound.Play(wx.SOUND_ASYNC)   else:    wx.MessageBox("Invalid sound file", "Error")    app = wx.PySimpleApp() frm = MyFrame() frm.Show() app.MainLoop() 

Instance 2

import wx import wx.media import os  class Panel1(wx.Panel):  def __init__(self, parent, id):   #self.log = log   wx.Panel.__init__(self, parent, -1, style=wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN)    # Create some controls   try:    self.mc = wx.media.MediaCtrl(self, style=wx.SIMPLE_BORDER)   except NotImplementedError:    self.Destroy()    raise    loadButton = wx.Button(self, -1, "Load File")   self.Bind(wx.EVT_BUTTON, self.onLoadFile, loadButton)      playButton = wx.Button(self, -1, "Play")   self.Bind(wx.EVT_BUTTON, self.onPlay, playButton)      pauseButton = wx.Button(self, -1, "Pause")   self.Bind(wx.EVT_BUTTON, self.onPause, pauseButton)      stopButton = wx.Button(self, -1, "Stop")   self.Bind(wx.EVT_BUTTON, self.onStop, stopButton)    slider = wx.Slider(self, -1, 0, 0, 0, size=wx.Size(300, -1))   self.slider = slider   self.Bind(wx.EVT_SLIDER, self.onSeek, slider)      self.st_file = wx.StaticText(self, -1, ".mid .mp3 .wav .au .avi .mpg", size=(200,-1))   self.st_size = wx.StaticText(self, -1, size=(100,-1))   self.st_len = wx.StaticText(self, -1, size=(100,-1))   self.st_pos = wx.StaticText(self, -1, size=(100,-1))      # setup the button/label layout using a sizer   sizer = wx.GridBagSizer(5,5)   sizer.Add(loadButton, (1,1))   sizer.Add(playButton, (2,1))   sizer.Add(pauseButton, (3,1))   sizer.Add(stopButton, (4,1))   sizer.Add(self.st_file, (1, 2))   sizer.Add(self.st_size, (2, 2))   sizer.Add(self.st_len, (3, 2))   sizer.Add(self.st_pos, (4, 2))   sizer.Add(self.mc, (5,1), span=(5,1)) # for .avi .mpg video files   self.SetSizer(sizer)    self.timer = wx.Timer(self)   self.Bind(wx.EVT_TIMER, self.onTimer)   self.timer.Start(100)     def onLoadFile(self, evt):   dlg = wx.FileDialog(self, message="Choose a media file",        defaultDir=os.getcwd(), defaultFile="",        style=wx.OPEN | wx.CHANGE_DIR )   if dlg.ShowModal() == wx.ID_OK:    path = dlg.GetPath()    self.doLoadFile(path)   dlg.Destroy()     def doLoadFile(self, path):   if not self.mc.Load(path):    wx.MessageBox("Unable to load %s: Unsupported format?" % path, "ERROR", wx.ICON_ERROR | wx.OK)   else:    folder, filename = os.path.split(path)    self.st_file.SetLabel('%s' % filename)    self.mc.SetBestFittingSize()    self.GetSizer().Layout()    self.slider.SetRange(0, self.mc.Length())    self.mc.Play()     def onPlay(self, evt):   self.mc.Play()    def onPause(self, evt):   self.mc.Pause()    def onStop(self, evt):   self.mc.Stop()    def onSeek(self, evt):   offset = self.slider.GetValue()   self.mc.Seek(offset)   def onTimer(self, evt):   offset = self.mc.Tell()   self.slider.SetValue(offset)   self.st_size.SetLabel('size: %s ms' % self.mc.Length())   self.st_len.SetLabel('( %d seconds )' % (self.mc.Length()/1000))   self.st_pos.SetLabel('position: %d ms' % offset)   app = wx.PySimpleApp() # create a window/frame, no parent, -1 is default ID frame = wx.Frame(None, -1, "play audio and video files", size = (320, 350)) # call the derived class Panel1(frame, -1) frame.Show(1) app.MainLoop() 

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.