Play sound in Python - GeeksforGeeks

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?