We want to play only the first 14 seconds of a 30-second audio.
# Play only the first 14 seconds of the audio
import librosa
import numpy as np
from pydub import AudioSegment
# Load only the first 14 seconds of the audio
file_path = 'bakushin.mp3'
# Load audio (only first 14 seconds)
y, sr = librosa.load(file_path, duration=14)
# Step 2: Convert librosa audio (numpy array) to pydub AudioSegment
# pydub expects raw audio in 16-bit PCM format
# Convert float32 [-1, 1] to int16
# 2 bytes for int16
# librosa loads in mono by default
y_16bit = np.int16(y * 32767)
audio_segment = AudioSegment(y_16bit.tobytes(), frame_rate=sr,
sample_width=2, channels=1)
# Export using pydub
output_file = "bakushin_2.mp3"
audio_segment.export(output_file, format="mp3", bitrate="192k")
print(f"Exported first 14 seconds to: {output_file}")
Output: