如何使用WMPlayer.OCX实现指定文件夹内歌曲的连续逐个播放?
Fix: Play All Songs in a Folder Consecutively with WMPlayer.OCX
Let's tweak your code to automatically play every song in your target folder one after another—no manual track switching needed. Here's the revised version, plus a breakdown of the key changes:
Revised Working Code
import os import time from win32com.client import Dispatch songs_dir = 'G:\\songs\\My Fav' mp = Dispatch("WMPlayer.OCX") # Loop through all files in the songs folder and build the playlist for song_file in os.listdir(songs_dir): # Optional: Filter for common audio formats to skip non-music files if song_file.lower().endswith(('.mp3', '.wav', '.flac', '.m4a')): full_song_path = os.path.join(songs_dir, song_file) track = mp.newMedia(full_song_path) mp.currentPlaylist.appendItem(track) # Start playing the entire playlist (WMPlayer auto-plays the next track when one ends) mp.controls.play() print("Playing all songs in the folder...") # Wait for user input to stop playback input("Press Enter to stop playing") mp.controls.stop()
Key Changes Explained
- Added
import os: Your original code usedos.listdir()but missed importing theosmodule, which would have thrown an error. - Traversed all folder files: Instead of hardcoding a single track (
songs[2]), we loop through every file in the directory to add all songs to the playlist. - Optional audio format filter: Added a check to only process files with common audio extensions (feel free to add/remove formats like
.oggor.wmaas needed) to avoid errors from non-music files in the folder. - Played the full playlist: Instead of targeting a single track with
playItem(), we start the entire playlist withmp.controls.play()—WMPlayer will automatically move to the next song when the current one finishes. - Removed unnecessary lines: The
time.sleep(1)andmp.controls.playItem(tune)calls are no longer needed since we're playing the full playlist directly.
This setup will keep playing songs in order until you press Enter to stop.
内容的提问来源于stack exchange,提问作者Kongu B K Riot
相关产品推荐
相关产品推荐

