Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
#Delete the directory if its empty in the beginning itself
if not filenames:
try:
os.rmdir(dirpath)
except OSError: pass
if self.args.verbose:
logger.debug(dirpath + "deleted as its empty")
for mp3_file in filenames:
#Operate only on mp3s
if mp3_file[-3:] != "mp3":
continue
files_done += 1
src = os.path.join(dirpath, mp3_file)
music_file = audiofile.AudioFile(src)
meta_data = [music_file.getArtist(), music_file.getAlbum(), music_file.getTitle()]
#Replace metadata if required. like the shitty www.songs.pk.
#Artist
if self.args.editartist is not None:
meta_data[0] = meta_data[0].replace(self.args.editartist[0],self.args.editartist[1])
music_file.setArtist(meta_data[0])
#Album
if self.args.editalbum is not None:
meta_data[1] = meta_data[1].replace(self.args.editalbum[0],self.args.editalbum[1])
music_file.setAlbum(meta_data[1])
#Title
if self.args.edittitle is not None:
meta_data[2] = meta_data[2].replace(self.args.edittitle[0],self.args.edittitle[1])
music_file.setTitle(meta_data[2])
def shift(sigin, pitch):
if np.isnan(pitch):
return sigin
input_filepath = "./.shift_input.wav"
output_filepath = "./.shift_output.wav"
shift_input = AudioFile.gen_default_wav(
input_filepath,
overwrite_existing=True,
mode='w',
channels=1,
)
# Write grain to be shifted to file
shift_input.write_frames(sigin)
# Close file
del shift_input
cents = 1200. * np.log2(pitch)
p_shift_args = ["sox", input_filepath, output_filepath, "pitch", str(cents)]
p = subprocess.Popen(p_shift_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, err) = p.communicate()
overwrite_existing=True,
mode='w',
channels=1,
)
# Write grain to be shifted to file
shift_input.write_frames(sigin)
# Close file
del shift_input
cents = 1200. * np.log2(pitch)
p_shift_args = ["sox", input_filepath, output_filepath, "pitch", str(cents)]
p = subprocess.Popen(p_shift_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, err) = p.communicate()
with AudioFile(output_filepath, mode='r') as shift_output:
# Read result
result = shift_output.read_grain()
return result
raise RuntimeError("There is no match data to synthesize. The match program may need to be run first.")
for job_ind, (name, job) in enumerate(jobs):
# Generate output file name/path
filename, extension = os.path.splitext(name)
output_name = ''.join((filename, '_output', extension))
output_path = os.path.join(self.output_db.subdirs["audio"], output_name)
# Create audio file to save output to.
output_config = self.config.output_file
grain_matches = self.output_db.data["match"][name]
# Get the grain size and overlap used for analysis.
match_grain_size = grain_matches.attrs["grain_size"]
match_overlap = grain_matches.attrs["overlap"]
_grain_size = grain_size
with AudioFile(
output_path,
"w",
samplerate=output_config["samplerate"],
format=output_config["format"],
channels=output_config["channels"]
) as output:
hop_size = (grain_size / overlap) * output.samplerate/1000
_grain_size *= int(output.samplerate / 1000)
output_frames = np.zeros(_grain_size*2 + (int(hop_size*len(grain_matches))))
offset = 0
for target_grain_ind, matches in enumerate(grain_matches):
# If there are multiple matches, choose a match at random
# from available matches.
match_index = np.random.randint(matches.shape[0])
match_db_ind, match_grain_ind = matches[match_index]
with self.match_db.analysed_audio[match_db_ind] as match_sample:
datapath = os.path.join(subdir_paths['data'], 'analysis_data.hdf5')
try:
self.data = h5py.File(datapath, 'a')
except IOError:
raise IOError("Unable to create/append to file: {0}\nThis may be "
"due to another instance of this program running or a "
"corrupted HDF5 file.\n Make sure this is the only "
"running instance and regenerate HDF5 if "
"neccesary.".format(datapath))
self.analysed_audio = []
for item in self.audio_file_list:
filepath = os.path.join(subdir_paths['audio'], os.path.basename(item))
# if there is no wav file then skip
try:
with AnalysedAudioFile(
filepath,
'r',
data_file=self.data,
analyses=self.analysis_list,
name=os.path.basename(item),
db_dir=self.db_dir,
reanalyse=reanalyse,
config=self.config
) as AAF:
AAF.create_analysis()
self.analysed_audio.append(AAF)
except IOError as err:
# Skip any audio file objects that can't be analysed
self.logger.warning("File cannot be analysed: {0}\nReason: {1}\n"
"Skipping...".format(item, err))
exc_type, exc_value, exc_traceback = sys.exc_info()
def main():
#Parse arguments
main_args = parse_arguments()
#check_args(main_args)
# ----------
# Begin processing audio files here:
# ----------
# Creates a database structure at the location given and returns a list of
# AnalysedAudioObjects for each item in the database
database = af.AudioDatabase(main_args.database)
database.generate_analyses()
"""
#Create audio file instances
input_audio = af.AnalysedAudioFile(main_args.input_file, mode = 'r')
output_audio = af.AnalysedAudioFile(
main_args.output_file,
mode = 'w',
format = input_audio.format(),
channels = input_audio.channels(),
samplerate = input_audio.samplerate()
)
if main_args.verbose > 1:
input_audio.audio_file_info()
output_audio.audio_file_info()
"""
Returns:
tuple:
* **numpy.ndarray**: two-dimensional array with shape
`(channels, samples)`
* **int**: sample rate of the audio file
Example:
>>> signal, sampling_rate = load('speech.wav')
"""
signal = np.array([[]]) # empty signal of shape (1, 0)
sampling_rate = None
try:
signal, sampling_rate = af.read(filename,
duration=duration,
offset=offset,
always_2d=True)
except ValueError:
warn('File opening error for: {}'.format(filename), UserWarning)
except (IOError, FileNotFoundError):
warn('File does not exist: {}'.format(filename), UserWarning)
except RuntimeError:
warn('Runtime error for file: {}'.format(filename), UserWarning)
except subprocess.CalledProcessError:
warn('ffmpeg conversion failed for: {}'.format(filename), UserWarning)
return signal, sampling_rate