Play sound in Python - GeeksforGeeks
文章推薦指數: 80 %
Play sound in Python · The playsound module contains only a single function named playsound(). · It requires one argument: the path to the file ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPlaysoundinPythonWorkingwithwavfilesinPythonusingPydubAudioprocessingusingPydubandGooglespeechRecognitionAPIPython|SpeechrecognitiononlargeaudiofilesYoutubeDataAPISubscription|Set-3YoutubeDataAPISubscription|Set-1Python:ConvertSpeechtotextandtexttoSpeechSpeechRecognitioninPythonusingGoogleSpeechAPIConvertTexttoSpeechinPythonPythonTextToSpeech|pyttsxmoduleText-To-SpeechchangingvoiceinPythonPersonalVoiceAssistantinPythonVoiceAssistantusingpythonBuildaVirtualAssistantUsingPythonPython|CreateasimpleassistantusingWolframAlphaAPI.JunkFileOrganizerinPythonDesktopNotifierinPythonPythonDesktopNewsNotifierin20linesMorseCodeTranslatorInPythonSimpleChatRoomusingPythonSocketProgramminginPythonSocketProgrammingwithMulti-threadinginPythonMultithreadinginPython|Set1MultithreadinginPython|Set2(Synchronization)SynchronizationandPoolingofprocessesinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframePlaysoundinPythonWorkingwithwavfilesinPythonusingPydubAudioprocessingusingPydubandGooglespeechRecognitionAPIPython|SpeechrecognitiononlargeaudiofilesYoutubeDataAPISubscription|Set-3YoutubeDataAPISubscription|Set-1Python:ConvertSpeechtotextandtexttoSpeechSpeechRecognitioninPythonusingGoogleSpeechAPIConvertTexttoSpeechinPythonPythonTextToSpeech|pyttsxmoduleText-To-SpeechchangingvoiceinPythonPersonalVoiceAssistantinPythonVoiceAssistantusingpythonBuildaVirtualAssistantUsingPythonPython|CreateasimpleassistantusingWolframAlphaAPI.JunkFileOrganizerinPythonDesktopNotifierinPythonPythonDesktopNewsNotifierin20linesMorseCodeTranslatorInPythonSimpleChatRoomusingPythonSocketProgramminginPythonSocketProgrammingwithMulti-threadinginPythonMultithreadinginPython|Set1MultithreadinginPython|Set2(Synchronization)SynchronizationandPoolingofprocessesinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframePlaysoundinPythonViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 13Jan,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Inthisarticle,wewillseehowtoplaysoundinPythonusingsomeofthemostpopularaudiolibraries.Wewilllearnaboutthevariousmethodsforplayingsound.Method1:UsingplaysoundmoduleRunthefollowingcommandtoinstallthepackages:pipinstallplaysoundTheplaysoundmodulecontainsonlyasinglefunctionnamedplaysound().Itrequiresoneargument:thepathtothefilewiththesoundwehavetoplay.Itcanbealocalfile,oraURL.There’sanoptionalsecondargument,block,whichissettoTruebydefault.WecansetittoFalseformakingthefunctionrunasynchronously.ItworkswithbothWAVandMP3files.Example:ForWAVformatPython3#importrequiredmodulefromplaysoundimportplaysound #forplayingnote.wavfileplaysound('/path/note.wav')print('playingsoundusing playsound')Output:https://media.geeksforgeeks.org/wp-content/uploads/20210102134813/gfgplaysound.mp4Example:Formp3formatPython3#importrequiredmodulefromplaysoundimportplaysound #forplayingnote.mp3fileplaysound('/path/note.mp3')print('playingsoundusing playsound')Output:https://media.geeksforgeeks.org/wp-content/uploads/20210102134813/gfgplaysound.mp4Method2:UsingpydubmoduleRunthefollowingcommandstoinstallthepackages:sudoapt-getinstallffmpeglibavcodec-extra pipinstallpydubNote:YoucanopenWAVfileswithpython.Foropeningmp3,you’llneedffmpegorlibav.Thismoduleusesthefrom_wav()methodforplayingwavfileandfrom_mp3()methodforplayinganmp3file. Theplay()methodisusedtoplaythewavandmp3file:Example1:ForWAVformatPython3#importrequiredmodulesfrompydubimportAudioSegmentfrompydub.playbackimportplay #forplayingwavfilesong=AudioSegment.from_wav("note.wav")print('playingsoundusing pydub')play(song)Output:https://media.geeksforgeeks.org/wp-content/uploads/20210102134814/gfgpydub.mp4Example2:Formp3formatPython3#importrequiredmodulefrompydubimportAudioSegmentfrompydub.playbackimportplay #forplayingmp3filesong=AudioSegment.from_mp3("note.mp3")print('playingsoundusing pydub')play(song)Output:https://media.geeksforgeeks.org/wp-content/uploads/20210102134814/gfgpydub.mp4Method3:UsingtksnackmoduleThetksnackmoduledependsuponamodulenamedtkintertoactivateatkobjectinthepythonscript.YoumustinstalltkinkerandtksnackpackagesforPython.Runthefollowingcommandstoinstallthepackages:sudoapt-getinstallpython3-tk sudoapt-getinstallpython3-tksnackTheplay()methodisusedtoplaytheaudiofiles.Theblockingargumentstatesthatthesoundwillplayasynchronously.Example: Python3#importrequiredmodulesfromTkinterimport*importtkSnack #initializetkobjecttousetksnackroot=Tk()tkSnack.initializeSnack(root) #playsoundsnd=tkSnack.Sound()snd.read('note.wav')print('playingsoundusingtkSnack')snd.play(blocking=1)Output:https://media.geeksforgeeks.org/wp-content/uploads/20210102134818/gfgtksnack.mp4Method4:UsingNativePlayerInthismethod,weplaysoundsnativelyonoursystem.Thismethodplaystheaudiofilewithanexternalplayerinstalledonyourterminal.Example1:ForMacOSXPython3#importrequiredmoduleimportos #playsoundfile="note.wav"print('playingsoundusingnativeplayer')os.system("afplay"+file)Output:https://media.geeksforgeeks.org/wp-content/uploads/20210102134811/gfgnativeplayer.mp4Example2:ForLinuxPython3#importrequiredmoduleimportos #playsoundfile="note.mp3"print('playingsoundusingnativeplayer')os.system("mpg123"+file)Output:https://media.geeksforgeeks.org/wp-content/uploads/20210102134811/gfgnativeplayer.mp4Method5:UsingsimpleaudiomoduleThisismainlydesignedtoplayWAVfilesandNumPyarrays.Runthefollowingcommandtoinstallthepackages:$sudoapt-getinstalllibasound2-dev $pip3installsimpleaudioTheplay()methodisusedtoplaytheaudiofiles.Example:Python3#importrequiredmoduleimportsimpleaudioassa #defineanobjecttoplaywave_object=sa.WaveObject.from_wave_file('note.wav)print('playingsoundusingsimpleaudio') #defineanobjecttocontroltheplayplay_object=wave_object.play()play_object.wait_done()Output:https://media.geeksforgeeks.org/wp-content/uploads/20210102134816/gfgsimpleaudio.mp4MyPersonalNotes arrow_drop_upSave LikeNext WorkingwithwavfilesinPythonusingPydubRecommendedArticlesPage:01,May1804,Oct1909,Aug2009,Aug2009,Aug2017,Aug2013,Jan2122,Jan2123,Jul2215,Oct1820,Jul2015,Sep2016,Sep2025,Feb1631,Jul1906,Jun1911,Jun1911,Jun1912,Jun1917,Aug1902,Sep1926,Sep1904,Mar2021,Apr20ArticleContributedBy:chetankhanna767@chetankhanna767VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertArticleTags:Pickedpython-utilityPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Trying to play an MP3 through python with playsound. Not ...
#!/usr/bin/env python # import required module from playsound import playsound # for playing note...
- 2Python实用模块(二十九)playsound - 迷途小书童的Note - 编程
playsound 支持多平台,仅仅依赖于 python 。 安装. 官方给出的安装方法是 pip install playsound. 但是我在执行的时候, ...
- 3playsound - PyPI
Pure Python, cross platform, single function module with no dependencies for playing sounds.
- 4playsound的简介、安装、使用方法之详细攻略 - CSDN博客
playsound的简介. 纯Python,跨平台,单功能模块,不依赖播放声音。 播放声音模块只包含一个东西——函数(也 ...
- 5Python playsound - play mp3 sound files - CodersLegacy
The Python playsound library offers an easy and simple way to play sound files in Python. From al...