i have a script to play a random wav file from a folder works good but Il like it to only play between 9am and 5pm not sure how to do that
Thanks
from os.path import isfile, join
import random
#path you want to get wav files from
path = "C:\Windows\Media"
onlyfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]
onlywavfiles = []
for f in onlyfiles:
if f[-3:] == "wav":
onlywavfiles.append(f)
#generate random number based on number of available files
randomnum = random.randint(0,len(onlywavfiles)-1)
eg.plugins.System.PlaySound(path + "/" + onlywavfiles[randomnum], 1, False)
Because you did not say what triggers that script, I' ll have to guess.
I guess: The script is triggered by an event from your home automation. Perhaps someone rings the bell, or Balto requests his meal, or a fish jumps out of the aquarium.
That triggers an event and starts the script. The script plays a random wav file from the Media folder.
But you don't want the music to be played outside the interval you specified.
It doesn't matter, if the script is still executed/triggered, only the sound must not be played.
You could simply read the time, extract the hour and test 9 < hour or hour > 16
and return from the script before the sound is played if the test is true.
(I'm from Germany so we have 24 hour time. I dont know how python returns hours for 12 hr systems.)
from os.path import isfile, join
import random
import datetime
hr = datetime.datetime.now().hour
if hr < 9 or hr > 16:
exit()
#path you want to get wav files from
path = "C:\Windows\Media"
onlyfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]
onlywavfiles = []
for f in onlyfiles:
if f[-3:] == "wav":
onlywavfiles.append(f)
#generate random number based on number of available files
randomnum = random.randint(0,len(onlywavfiles)-1)
eg.plugins.System.PlaySound(path + "/" + onlywavfiles[randomnum], 1, False)
Related
Using the progressbar library :
import progressbar
.
.
bar = progressbar.ProgressBar(maxval=len(files_total)).start()
This is my base for loop to read and store all .txt files in path4safe (which is a local test folder with 200 .txt file), which also tell me how many text files there is in the folder with a "d"
for root, dirnames, files in os.walk(path4safe):
for x in files:
if x.endswith(tuple(ext)):
d += 1
files_total.append(root + "/" + x)
So I tried this :
for root, dirnames, files in os.walk(path4safe):
for idx, files in enumerate(files_total):
for x in files:
if x.endswith(tuple(ext)):
d += 1
files_total.append(root + "/" + x)
bar.update(idx)
But I only get an empty progress bar, I feel like I'm mixing up one of my var. Basically I'm trying to use "d" to create the progressbar.
[]0% | |
Total files:
0
I am writing a simple Python script to tell me file size for a set of documents which I am importing from a CSV. I verified that none of the entries are over 100 characters, so this error "ValueError: scandir: path too long for Windows" does not make sense to me.
Here is my code:
# determine size of a given folder in MBytes
import os, subprocess, json, csv, platform
# Function to check if a Drive Letter exists
def hasdrive(letter):
return "Windows" in platform.system() and os.system("vol %s: 2>nul>nul" % (letter)) == 0
# Define Drive to check for
letter = 'S'
# Check if Drive doesnt exist, if not then map drive
if not hasdrive(letter):
subprocess.call(r'net use s: /del /Y', shell=True)
subprocess.call(r'net use s: \\path_to_files', shell=True)
list1 = []
# Import spreadsheet to calculate size
with open('c:\Temp\files_to_delete_subset.csv') as f:
reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
for row in reader:
list1.extend(row)
# Define variables
folder = "S:"
folder_size = 0
# Exporting outcome
for list1 in list1:
folder = folder + str(list1)
for root, dirs, files in os.walk(folder):
for name in files:
folder_size += os.path.getsize(os.path.join(root, name))
print(folder)
# print(os.path.join(root, name) + " " + chr(os.path.getsize(os.path.join(root, name))))
print(folder_size)
From my understanding the max path size in Windows is 260 characters, so 1 driver letter + 100 character path should NOT exceed the Windows max.
Here is an example of a path: '/Document/8669/CORRESP/1722165.doc'
The folder string you're trying to walk is growing forever. Simplifying the code to the problem area:
folder = "S:"
# Exporting outcome
for list1 in list1:
folder = folder + str(list1)
You never set folder otherwise, so it starts out as S:<firstpath>, then on the next loop it's S:<firstpath><secondpath>, then S:<firstpath><secondpath><thirdpath>, etc. Simple fix: Separate drive from folder:
drive = "S:"
# Exporting outcome
for path in list1:
folder = drive + path
Now folder is constructed from scratch on each loop, throwing away the previous path, rather than concatenating them.
I also gave the iteration value a useful name (and removed the str call, because the values should all be str already).
Im trying to write a basic program that picks 2 audio files at random, layers them, and writes it out as a new file. I'm using pydub and it all works, however the results are distorted. I suspect it's because from what I've learnt, pydub cannot handle 24 bit wavs, which happen to be the norm in sample packs.
So needing some small blip of code that converts the wav to 16 bit before it enters pydub. Hopefully not one that requires writing it to disc first.
from pydub import AudioSegment
import os
import random
import shutil
def process(user_folder):
new_library_folder = user_folder + " Generated Combo Samples"
files_list = []
for root, directory, files in os.walk(user_folder):
for file in files:
if file_is_valid_ext(file):
filepath = str(root) + "/" + str(file)
# print filepath
files_list.append(filepath)
# removes previously created folder
shutil.rmtree(new_library_folder)
os.makedirs(new_library_folder)
i = 0
for number in range(gen_count): # global at 100
i = i + 1
file1 = random.choice(files_list)
file2 = random.choice(files_list)
sound1 = AudioSegment.from_file(file1)
sound2 = AudioSegment.from_file(file2)
sound1 = match_target_amplitude(sound1, -20)
sound2 = match_target_amplitude(sound2, -20)
combinedsound = sound1.overlay(sound2)
combinedsoundnormalised = match_target_amplitude(combinedsound, -6)
combinedsound_path = new_library_folder + "/" + "Sample " + str(i) + ".wav"
combinedsoundnormalised.export(combinedsound_path, format='wav')
It has been some months since you posted this question but I will answer it for others who may need a solution to this. As far as I have found, PySoundFile is the only python package that can deal with 24 bit audio (I am sure there are others but I haven't found them). My suggestion would be to initially read in the audio using PySoundFile and then create a pydub.AudioSegment using that data.
I have a list of WAV files in a folder of data showing in the format of hours, minutes and second.
For example,
C:\Users\Desktop\Data
01h02m02s.wav
01h02m13s.wav
01h02m24s.wav
I need the filename to be modified, programmatically such that it needs to be converted into seconds. How do I do it?
3722s.wav
3733s.wav
3744s.wav
Would appreciate all feedback and help.
Thank you
Use glob.glob() to get your file list and then an regular expression to try and extract the hours, minutes and seconds from the filename. os.rename() is used to actually rename the file:
import glob
import re
import os
path = r'C:\Users\Desktop\Data'
for wav in glob.glob(os.path.join(path, '*.wav')):
re_hms = re.findall(r'(\d+)h(\d+)m(\d+)s\.wav', wav)
if re_hms:
hours, minutes, seconds = map(int, re_hms[0])
total_seconds = hours * 3600 + minutes * 60 + seconds
new_wav = os.path.join(path, '{}s.wav'.format(total_seconds))
print "{} -> {}".format(wav, new_wav)
os.rename(wav, new_wav)
os.path.join() is used to safely join file paths together without having to worry about adding path separators.
You could use this if all the files in the path are WAV and their names have the pattern as shown by you.
import os
path = r'C:\Users\Desktop\Data'
waves = os.listdir(path)
for wave in waves:
hours, minutes, seconds = map(int, [wave[:2], wave[3:5], wave[6:8]])
total_seconds = hours * 3600 + minutes * 60 + seconds
new_name = os.path.join(path, "{}s.wav".format(total_seconds))
os.rename(os.path.join(path, wave), new_name)
I got some episodes of a show downloaded onto my PC, but the titles are mixed up completely so it's hard to find the episode I want and I don't want to refer to the wiki to find out which episode is which
Since there's a too many episodes to individually rename them, I've decided to use python to rename all at once, using a json table to store the correct episodes name to compare and replace them (the episodes all have their season number and episode number so I can use that for the comparison)
Currently, I've got this:
import os
import sys
from random import randint as mathRandom
nameDict={}
#nameDict["Ed.Edd.n.Eddy.S01E01"]={"Name":"Ed Touchables / Nagged to Ed"}
nameDict["Ed.Edd.n.Eddy.S01E02"]={"Name":"Pop Goes the Ed / Over Your Ed"}
nameDict["Ed.Edd.n.Eddy.S01E03"]={"Name":"Sir Ed-a-Lot / A Pinch to Grow an Ed"}
nameDict["Ed.Edd.n.Eddy.S01E04"]={"Name":"Dawn of the Eds / Virt-Ed-Go"}
nameDict["Ed.Edd.n.Eddy.S01E05"]={"Name":"Read All About Ed / Quick Shot Ed"}
nameDict["Ed.Edd.n.Eddy.S01E06"]={"Name":"An Ed Too Many / Ed-n-Seek"}
nameDict["Ed.Edd.n.Eddy.S01E07"]={"Name":"Look into My Eds / Tag Yer Ed"}
nameDict["Ed.Edd.n.Eddy.S01E08"]={"Name":"Fool on the Ed / A Boy and His Ed"}
nameDict["Ed.Edd.n.Eddy.S01E09"]={"Name":"It's Way Ed / Laugh Ed Laugh"}
nameDict["Ed.Edd.n.Eddy.S01E10"]={"Name":"A Glass of Warm Ed / Flea-Bitten Ed"}
nameDict["Ed.Edd.n.Eddy.S01E11"]={"Name":"Who, What, Where, Ed! / Keeping Up with the Eds"}
nameDict["Ed.Edd.n.Eddy.S01E12"]={"Name":"Eds-Aggerate / Oath to an Ed"}
nameDict["Ed.Edd.n.Eddy.S01E13"]={"Name":"Button Yer Ed / Avast Ye Eds"}
path = 'C:/Users/badfitz66/Desktop/EdEddnEddy/Episodes'
os.chdir(path)
for filename in os.listdir(path):
filename_splitext = os.path.splitext(filename)
newSettings = nameDict[filename_splitext[0]].get("Name")
if newSettings is not None :
if nameDict.get(filename_splitext[0]):
os.rename(filename, filename + str(newSettings)+'.mkv')
I'm trying to change the episodes names that are the first values (eg: Ed.Edd.n.Eddy.S01E04) to the episode number and season + the name of each part (eg: Read All About Ed / Quick Shot Ed)
But when I run, I get this error:
Traceback (most recent call last):
File "C:/Users/badfitz66/Desktop/ah.py", line 33, in <module>
os.rename(filename, filename + str(newSettings)+'.mkv')
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Ed.Edd.n.Eddy.S01E02.mkv' -> 'Ed.Edd.n.Eddy.S01E02.mkvPop Goes the Ed / Over Your Ed.mkv'
What am I doing wrong?
In your for loop, episode is a string, not a dict. So you cannot access its elements using string index.
Just replace episode['Name'] with episode, and it renamed all my files.
You can use only 1 loop to get things done
import os
import sys
nameDict={}
nameDict["test.1"]={"Name":"LOL1.mkv"}
nameDict["test.2"]={"Name":"LOL2.vcl"}
nameDict["test.3"]={"Name":"LOL3.txt"}
nameDict["test.4"]={"Name":"LOL4.py"}
nameDict["test.5"]={"Name":"LOL5.ss"}
nameDict["test.6"]={"Name":"LOL6.lol"}
nameDict["test.7"]={"Name":"LOL7.po"}
path = 'test'
# Loop over all files and directories
for filename in os.listdir(path):
# Get the name
filename_splitext = os.path.splitext(filename)
# print filename_splitext
# Check if we have new file name in nameDict
newSettings = nameDict.get( str(filename_splitext[0]), None)
if newSettings is not None :
# print newSettings
# Rename with new filename
os.rename(os.path.join(path, filename),os.path.join(path, newSettings['Name']))
Shot in the dark:
Try episode.Name instead of episode["Name"]