Getting started with Python LanguageList comprehensionsFilterListFunctionsDecoratorsMath ModuleLoopsRandom moduleComparisonsImporting modulesSorting, Minimum and MaximumOperator moduleVariable Scope and BindingBasic Input and OutputFiles & Folders I/OJSON ModuleString MethodsMetaclassesIndexing and SlicingGeneratorsSimple Mathematical OperatorsReduceMap FunctionExponentiationSearchingDictionaryClassesCountingManipulating XMLDate and TimeSetCollections moduleParallel computationMultithreadingWriting extensionsUnit TestingRegular Expressions (Regex)Bitwise OperatorsIncompatibilities moving from Python 2 to Python 3Virtual environmentsCopying dataTupleContext Managers (“with” Statement)Hidden FeaturesEnumString FormattingConditionalsComplex mathUnicode and bytesThe __name__ special variableChecking Path Existence and PermissionsPython NetworkingAsyncio ModuleThe Print Functionos.pathCreating Python packagesParsing Command Line argumentsHTML ParsingSubprocess Librarysetup.pyList slicing (selecting parts of lists)SocketsItertools ModuleRecursionBoolean OperatorsThe dis moduleType Hintspip: PyPI Package ManagerThe locale ModuleExceptionsWeb scraping with PythonDeque ModuleDistributionProperty ObjectsOverloadingDebuggingReading and Writing CSVDynamic code execution with `exec` and `eval`PyInstaller - Distributing Python CodeIterables and IteratorsData Visualization with PythonThe Interpreter (Command Line Console)*args and **kwargsFunctools ModuleGarbage CollectionIndentationSecurity and CryptographyPickle data serialisationurllibBinary DataPython and ExcelIdiomsMethod OverridingDifference between Module and PackageData SerializationPython concurrencyIntroduction to RabbitMQ using AMQPStormPostgreSQLDescriptorCommon PitfallsMultiprocessingtempfile NamedTemporaryFileWorking with ZIP archivesStackProfilingUser-Defined MethodsWorking around the Global Interpreter Lock (GIL)DeploymentLoggingProcesses and ThreadsThe os ModuleComments and DocumentationDatabase AccessPython HTTP ServerAlternatives to switch statement from other languagesList destructuring (aka packing and unpacking)Accessing Python source code and bytecodeMixinsAttribute AccessArcPyPython Anti-PatternsPlugin and Extension ClassesWebsocketsImmutable datatypes(int, float, str, tuple and frozensets)String representations of class instances: __str__ and __repr__ methodsArraysOperator PrecedencePolymorphismNon-official Python implementationsList ComprehensionsWeb Server Gateway Interface (WSGI)2to3 toolAbstract syntax treeAbstract Base Classes (abc)UnicodeSecure Shell Connection in PythonPython Serial Communication (pyserial)Neo4j and Cypher using Py2NeoBasic Curses with PythonPerformance optimizationTemplates in pythonPillowThe pass statementLinked List Nodepy.testDate FormattingHeapqtkinterCLI subcommands with precise help outputDefining functions with list argumentsSqlite3 ModulePython PersistenceTurtle GraphicsConnecting Python to SQL ServerDesign PatternsMultidimensional arraysAudioPygletQueue ModuleijsonWebbrowser ModuleThe base64 ModuleFlaskgroupby()Sockets And Message Encryption/Decryption Between Client and ServerpygameInput, Subset and Output External Data Files using Pandashashlibgetting start with GZipDjangoctypesCreating a Windows service using PythonPython Server Sent EventsMutable vs Immutable (and Hashable) in PythonPython speed of programconfigparserLinked listsCommonwealth ExceptionsOptical Character RecognitionPython Data TypesPartial functionspyautogui modulegraph-toolUnzipping FilesFunctional Programming in PythonPython Virtual Environment - virtualenvsysvirtual environment with virtualenvwrapperCreate virtual environment with virtualenvwrapper in windowsPython Requests PostPlotting with MatplotlibPython Lex-YaccChemPy - python packagepyaudioshelveUsage of "pip" module: PyPI Package ManagerIoT Programming with Python and Raspberry PICode blocks, execution frames, and namespaceskivy - Cross-platform Python Framework for NUI DevelopmentCall Python from C#Similarities in syntax, Differences in meaning: Python vs. JavaScriptWriting to CSV from String or ListRaise Custom Errors / ExceptionsUsing loops within functionsPandas Transform: Preform operations on groups and concatenate the results

pygame

Other topics

Installing pygame

With pip:

pip install pygame

With conda:

conda install -c tlatorre pygame=1.9.2

Direct download from website : http://www.pygame.org/download.shtml

You can find the suitable installers fro windows and other operating systems.

Projects can also be found at http://www.pygame.org/

Pygame's mixer module

The pygame.mixer module helps control the music used in pygame programs. As of now, there are 15 different functions for the mixer module.

Initializing

Similar to how you have to initialize pygame with pygame.init(), you must initialize pygame.mixer as well.

By using the first option, we initialize the module using the default values. You can though, override these default options. By using the second option, we can initialize the module using the values we manually put in ourselves. Standard values:

pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)

To check whether we have initialized it or not, we can use pygame.mixer.get_init(), which returns True if it is and False if it is not. To quit/undo the initializing, simply use pygame.mixer.quit(). If you want to continue playing sounds with the module, you might have to reinitialize the module.

Possible Actions

As your sound is playing, you can pause it tempoparily with pygame.mixer.pause(). To resume playing your sounds, simply use pygame.mixer.unpause(). You can also fadeout the end of the sound by using pygame.mixer.fadeout(). It takes an argument, which is the number of milliseconds it takes to finish fading out the music.

Channels

You can play as many songs as needed as long there are enough open channels to support them. By default, there are 8 channels. To change the number of channels there are, use pygame.mixer.set_num_channels(). The argument is a non-negative integer. If the number of channels are decreased, any sounds playing on the removed channels will immediately stop.

To find how many channels are currently being used, call pygame.mixer.get_channels(count). The output is the number of channels that are not currently open. You can also reserve channels for sounds that must be played by using pygame.mixer.set_reserved(count). The argument is also a non-negative integer. Any sounds playing on the newly reserved channels will not be stopped.

You can also find out which channel isn't being used by using pygame.mixer.find_channel(force). Its argument is a bool: either True or False. If there are no channels that are idle and force is False, it will return None. If force is true, it will return the channel that has been playing for the longest time.

Syntax:

  • pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
  • pygame.mixer.pre_init(frequency, size, channels, buffer)
  • pygame.mixer.quit()
  • pygame.mixer.get_init()
  • pygame.mixer.stop()
  • pygame.mixer.pause()
  • pygame.mixer.unpause()
  • pygame.mixer.fadeout(time)
  • pygame.mixer.set_num_channels(count)
  • pygame.mixer.get_num_channels()
  • pygame.mixer.set_reserved(count)
  • pygame.mixer.find_channel(force)
  • pygame.mixer.get_busy()

Parameters:

ParameterDetails
countA positive integer that represents something like the number of channels needed to be reserved.
forceA boolean value (False or True) that determines whether find_channel() has to return a channel (inactive or not) with True or not (if there are no inactive channels) with False

Contributors

Topic Id: 8761

Example Ids: 27311,27450

This site is not affiliated with any of the contributors.