Thomas Karer said:
Hello!
I have the following problem.
There is a folder with mp3 files inside it.
I want to randomly pick a file an play this.
It would be great if there would be a way to get a random filename in a
variable.
thank you
tom
Since building a full list of files in the entire drive would take a while,
I've restricted the following scans to
C:\documents and settings\ as a local root. Adjust to suit...
----- batch begins -------
[1]@echo off
[2]setlocal
[3]:: create a tempfile of .mp3s, prefixed by [sequencenumber]
[4]dir /s/b/a-d "C:\documents and settings\*.mp3" | find /n /v ""
[5]:: find the Count of Files
[6]for /f "usebackq delims=[]" %%i in ("%temp%\mp3list.1") do set ycf=%%i
[7]:: now select at random from list
[8]set /a ysn=(%random% %% %ycf%) + 1
[9]for /f "usebackq tokens=1*delims=[]" %%i in ("%temp%\mp3list.1") do if
%%i==%ysn% set yts=%%j
[10]:: clean up tempfile
[11]del "%temp%\mp3list.1"
[12]endlocal&set music=%yts%
[13]echo track selected : %music%
------ batch ends --------
Lines start [number] - any lines not starting [number] have been wrapped
and should be rejoined. The [number] that starts the line should be removed
%temp% is a temporary directory. The environment variable %temp% is
set to "C:\Documents and Settings\username\temp" by default. Since
this contains spaces, it would probably be better to enclose any
such filename in quotes, thus: "%temp%\...." Experienced batchers
will change their %temp% to something more sensible, like C:\temp.
The issue is that it's a temporary file. Replace the pathname with one
that suits you, remembering that any tempfiles created may overwrite
existing files.
Note line [12] here. It uses the parsing characteristic of CMD.EXE to set a
variable to the value of a variable in the LOCAL context.
By extension,
----- batch begins -------
[1]@echo off
[2]setlocal
[3]del select.seq 2>nul
[4]:: create a tempfile of .mp3s, prefixed by [sequencenumber]
[5]dir /s/b/a-d "C:\documents and settings\*.mp3" | find /n /v ""
[6]:: find the Count of Files
[7]for /f "usebackq delims=[]" %%i in ("%temp%\mp3list.1") do set ycf=%%i
[8]:: now select at random from list
[9]:selloop
[10]set /a ysn=(%random% %% %ycf%) + 1
[11]for /f "usebackq tokens=1*delims=[]" %%i in ("%temp%\mp3list.1") do if
%%i==%ysn% (echo %%j>>select.seq) else (echo [%%i]%%j>>"%temp%\mp3list.2")
[12]:: clean up tempfile
[13]del "%temp%\mp3list.1"
[14]if exist "%temp%\mp3list.2" ren "%temp%\mp3list.2" mp3list.1&goto
selloop
[15]endlocal
[16]echo tracks selected :
[17]type select.seq
[18]
------ batch ends --------
will build a random list of all of the mp3s in "select.seq"