# importimportwave# Open the wave file and extract some propertiesfile_path=f'{dataset_folder}/call_1.wav'withwave.open(file_path,'rb')aswav_file:n_channels=wav_file.getnchannels()sample_width=wav_file.getsampwidth()frame_rate=wav_file.getframerate()n_frames=wav_file.getnframes()comp_type=wav_file.getcomptype()comp_name=wav_file.getcompname()# structure the required statswav_file_stats={"Number of Channels":n_channels,"Sample Width":sample_width,"Frame Rate":frame_rate,"Number of Frames":n_frames,"Compression Type":comp_type,"Compression Name":comp_name}# printprint(wav_file_stats)# Example output: # {'Number of Channels': 1,# 'Sample Width': 2,# 'Frame Rate': 22050,# 'Number of Frames': 3821760,# 'Compression Type': 'NONE',# 'Compression Name': 'not compressed'}
Get WAV file duration in seconds
1 2 3 4 5 6 7 8 910111213141516
# import importwavedefprint_wav_duration(file_path):# Open the wave filewithwave.open(file_path,'rb')aswav_file:# Extract the frame rate and number of framesframe_rate=wav_file.getframerate()n_frames=wav_file.getnframes()# Calculate durationduration=n_frames/float(frame_rate)print(f"The duration of the file is: {duration} seconds.")# Example usage with a placeholder file path# You would replace 'path/to/file.wav' with the actual file path of your .wav fileprint_wav_duration('path/to/file.wav')
importwaveimportnumpyasnpdefstereo_to_mono(file_path):# Open the stereo wave filewithwave.open(file_path,'rb')asstereo_wav:# Check if it's already monoifstereo_wav.getnchannels()!=2:return"The file is not a stereo file."# Read the stereo wave file dataframes=stereo_wav.readframes(stereo_wav.getnframes())# Convert frames to numpy arrayframes=np.frombuffer(frames,dtype=np.int16)# Reshape the data to 2 columns for stereoframes=np.reshape(frames,(-1,2))# Take the mean of the two channels to convert to monomono_frames=frames.mean(axis=1,dtype=np.int16)# Get stereo file params to use for mono fileparams=stereo_wav.getparams()num_frames=len(mono_frames)# Set the file path for outputmono_file_path=file_path.replace(".wav","_mono.wav")# Create a new wave file for monowithwave.open(mono_file_path,'wb')asmono_wav:# Set parameters for mono (nchannels=1)mono_wav.setparams((1,params.sampwidth,params.framerate,num_frames,params.comptype,params.compname))# Write frames for monomono_wav.writeframes(mono_frames.tobytes())returnf"Stereo file converted to mono: {mono_file_path}"# Replace with an actual file path to a stereo wav file# e.g., stereo_to_mono("path/to/stereo_file.wav")stereo_to_mono(f'{dataset_folder}/call_5.wav')