Anthony Drury
Anthony Drury

Reputation: 128

Python randomly playing VLC files in specific folder

I am trying to have it so that I can randomly play vlc files I have inside a specific folder, however I am getting the error.

>>> media.py
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'media' is not defined

I have navigated to the correct directory and the file is called media.py

My Code:

import os, random, subprocess
def rndmp(self):
   randomfile = random.choice(os.listdir("F:\\Work\\Python\\"))
   file = 'F:\\Work\\Python\\'+ randomfile
   subprocess.call(['F:\\Apps\\VLC\\vlc.exe', file])

rndmp()

Following this guide: Best way to choose a random file from a directory

And used another one which dealt with using subprocess to run vlc.exe

I am very new to python so I think I am missing something simple.

Upvotes: 0

Views: 2632

Answers (2)

Areeb
Areeb

Reputation: 406

You can simply create a .m3u file and play that via Python. Coincidentally I wrote a script just for that:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from threading import Timer

dir = "C:\Users\M4Shooter\Desktop\Music" # This is the directory where the audio files are, you can make it something like
                                         # C:\Users\M4Shooter\Desktop\Music\file.mp3 too, just to play a specific file

print "Playing ", dir
playlist = open('playlist.m3u', 'w')        # Create a temp playlist (if not present)
playlist.truncate()                         # Truncate / Erase the file data
playlist.write(dir + '\n')                  # Write's the directory path in 'dir' to the file
playlist.close()
os.system("playlist.m3u")                   # Opens the file with the default media player
remove = lambda : os.remove('playlist.m3u') # Function to remove the file
removeFile = Timer(20.0, remove)            # We need to wait for some seconds before removing the file,
removeFile.start()                          # To make sure that the media player loads the playlist

This code runs great on my system, you might want to add some conditional statements to check if the file exists before execution.

You can also replace 'dir' value with a path to an audio file. That way it will only add that specific file in the .m3u playlist.

Upvotes: 0

user5903421
user5903421

Reputation:

The error is in how you are trying to run your file.

To run from Python (like you tried earlier):

>>> import media
>>> media.rndmp()

Or open command line (if you are in Windows) and type:

python media.py

Upvotes: 2

Related Questions