You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 used os.listdir() but missed importing the os module, 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 .ogg or .wma as 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 with mp.controls.play()—WMPlayer will automatically move to the next song when the current one finishes.
  • Removed unnecessary lines: The time.sleep(1) and mp.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:07:39