To modify the given script to support reading segments from audio files when 'start' and 'end' are specified in the sample, it needs to handle the reading of specific time slices of the audio. Let's implement this by ensuring it reads the audio portion from start to end:
import io
import torchaudio
def process_audio_segment(wav_file, sample):
"""
Reads the audio segment specified by 'start' and 'end' in the sample,
or the full audio if 'start' and 'end' are not provided.
Args:
wav_file (bytes): The audio file in bytes format.
sample (dict): The sample containing 'start' and 'end' time and other metadata.
Returns:
dict: The sample with updated 'wav' containing the audio segment and 'sample_rate'.
"""
if 'start' in sample:
assert 'end' in sample, "If 'start' is specified in sample, 'end' must also be specified."
# Get the sample rate to convert start and end time to frames
sample_rate = torchaudio.info(io.BytesIO(wav_file)).sample_rate
start_frame = int(sample['start'] * sample_rate)
end_frame = int(sample['end'] * sample_rate)
# Load the audio segment
with io.BytesIO(wav_file) as file_obj:
waveform, _ = torchaudio.load(file_obj, num_frames=end_frame - start_frame, frame_offset=start_frame)
else:
# Load the entire audio file
with io.BytesIO(wav_file) as file_obj:
waveform, sample_rate = torchaudio.load(file_obj)
# Clean up and update the sample with the new audio data
sample.pop('wav', None)
sample['wav'] = waveform # Overwrite or add the waveform data
sample['sample_rate'] = sample_rate
return sample
# Example usage
# wav_file = ... # wav_file should be bytes
# sample = {
# 'start': 10.0, # Start time in seconds
# 'end': 20.0 # End time in seconds
# }
# processed_sample = process_audio_segment(wav_file, sample)
Description of Changes:
- Ensuring
end is provided if start is specified: Added an assertion to ensure end is present if start is specified in the sample.
- Using
torchaudio.info(io.BytesIO(wav_file)) to get sample rate: This ensures the sample rate is obtained correctly from the audio file in bytes format.
- Converting time to frame indices: Converted
start and end times from seconds to frame indices.
- Loading audio segment or full audio: Depending on whether
start and end are specified, either load the specified segment or the entire audio file.
- Updating the sample: Updated the sample with the new waveform and sample rate, making sure to remove the old 'wav' entry before updating.
Now the function should correctly handle reading specific segments of an audio file.