jsPRO

Untitled

Feb 6th, 2026
841
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. import os
  2. import subprocess
  3. import wmi
  4. import time
  5. import re
  6. import tempfile
  7.  
  8. VLC_PATH = r"C:\Program Files\VideoLAN\VLC\vlc.exe"
  9.  
  10. def get_sort_key(filename):
  11. """
  12. Extracts the leading number for numerical sorting.
  13. Handles '1 song', '10 song', '2 song' correctly.
  14. """
  15. # Look for any digit(s) at the very start of the filename
  16. match = re.match(r'^(\d+)', filename)
  17. if match:
  18. # Converting to int ensures 2 comes before 12
  19. return int(match.group(1))
  20. return 999999
  21.  
  22. def play_in_vlc(drive_letter):
  23. print(f"Scanning {drive_letter} for MP3s...")
  24. mp3_paths = []
  25.  
  26. for root, dirs, files in os.walk(drive_letter):
  27. for file in files:
  28. if file.lower().endswith(".mp3"):
  29. mp3_paths.append(os.path.join(root, file))
  30.  
  31. if not mp3_paths:
  32. return None
  33.  
  34. # SORTING LOGIC:
  35. # This sorts by the integer value of the leading number.
  36. mp3_paths.sort(key=lambda x: get_sort_key(os.path.basename(x)))
  37.  
  38. with tempfile.NamedTemporaryFile(mode='w', suffix='.m3u', delete=False) as f:
  39. for path in mp3_paths:
  40. f.write(path + '\n')
  41. playlist_path = f.name
  42.  
  43. print(f"Playing {len(mp3_paths)} files in numerical order.")
  44. return subprocess.Popen([VLC_PATH, playlist_path])
  45.  
  46. def monitor_drive():
  47. c = wmi.WMI()
  48. watcher = c.Win32_LogicalDisk.watch_for("creation")
  49. vlc_process = None
  50.  
  51. print("System active. Waiting for CD...")
  52.  
  53. while True:
  54. try:
  55. # Short timeout allows us to check for ejection frequently
  56. new_drive = watcher(timeout_ms=2000)
  57. if new_drive.DriveType == 4:
  58. drive_path = f"{new_drive.DeviceID}\\"
  59. time.sleep(3)
  60.  
  61. if vlc_process and vlc_process.poll() is None:
  62. vlc_process.terminate()
  63.  
  64. vlc_process = play_in_vlc(drive_path)
  65.  
  66. except wmi.x_wmi_timed_out:
  67. # Check if disc was removed
  68. if vlc_process and vlc_process.poll() is None:
  69. # If no CD drives have media, the disc was likely ejected
  70. ready_drives = [d for d in c.Win32_LogicalDisk(DriveType=4) if d.Size is not None]
  71. if not ready_drives:
  72. print("Disc ejected. Stopping playback...")
  73. vlc_process.terminate()
  74. vlc_process = None
  75. except Exception as e:
  76. time.sleep(1)
  77.  
  78. if __name__ == "__main__":
  79. monitor_drive()
Advertisement