make python simple script to play mp3 or wav file by user have to rename both of file…
- User
make python simple script to play mp3 or wav file by user have to rename both of file are same python_script exe and sound file
- Assistant
Certainly! You can create a simple Python script that plays an MP3 or WAV file with the requirement that the audio file has to have the same name as the script itself (except for the file extension). Below is an example of how to accomplish this using the
pygamelibrary to handle audio playback.Step 1: Install Required Library
If you haven't already, you need to install the
pygamelibrary, which will help us play audio files. You can install it using pip:bashpip install pygameStep 2: Create the Python Script
You can use the following Python script. Save it as
python_script.py(or whatever name you prefer).pythonimport os import sys import pygame # Initialize Pygame mixer pygame.mixer.init() # Get the name of the script without extension script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] # Define the audio files mp3_file = f"{script_name}.mp3" wav_file = f"{script_name}.wav" # Check if either the mp3 or wav file exists if os.path.isfile(mp3_file): audio_file = mp3_file elif os.path.isfile(wav_file): audio_file = wav_file else: print(f"No audio file found with the name {script_name}.mp3 or {script_name}.wav") sys.exit() # Load and play the audio file pygame.mixer.music.load(audio_file) print(f"Playing {audio_file}...") pygame.mixer.music.play() # Keep the program running until the music stops while pygame.mixer.music.get_busy(): pygame.time.Clock().tick(10)Step 3: Prepare Your Audio Files
Make sure you have your audio files named exactly like the script, with the correct extension. For example, if you saved the script as
python_script.py, then you should have:python_script.mp3orpython_script.wav
Step 4: Run the Script
- Save the Python script in the same directory as your audio file.