在开发万码学堂的铃声系统时,有个需求,需要从某个音乐文件夹下随机取出其中几个歌曲播放。
如何随机取出几个歌曲文件呢?
大体思路是先将某个目录中的文件全部取出放到数组中,然后随机取出其中几首。
给出某个目录中的文件代码:
def TimeStampToTime(timestamp):
timeStruct = time.localtime(timestamp)
return time.strftime('%Y%m%d',timeStruct)
def get_FileCreateTime(filePath):
t = os.path.getctime(filePath)
return TimeStampToTime(t)
#列出wanmait.com今天的歌曲文件(比如扩展名是.mp3或者.wav等)
def get_dir_mp3files(fileroot):
mp3files = []
if not os.path.isdir(fileroot):
return mp3files
files = os.listdir(fileroot)
for file in files:
if os.path.splitext(file)[1] in '.mp3,.wav,.m4a,.wma':
mp3 = os.path.join(fileroot, file)
mp3_time = get_FileCreateTime(mp3)
mp3files.append((mp3,int(mp3_time)))
return mp3files这就拿到了fileroot目录中的全部歌曲文件,接下来取出其中几首:
def get_random_music(dir,count):
'''
从指定目录dir选取count个随机歌曲
:param dir:
:param count:
:return:
'''
#fileroot = r'e:\mp4\am'
if not os.path.isdir(dir): return [('',0)*count]
mp3filestemp = get_dir_mp3files(dir)
#随机选取
mp3filestemp = random.sample(mp3filestemp,k=tcount)
return mp3filestemp那假如现在需求是:看看目录中歌曲文件是否今天新下载的歌曲,如果有,首先新下载的歌曲。如果没有再从其他文件中随机选,但是越新的歌曲,概率越大。如何实现?

0条评论
点击登录参与评论