help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
music-classification
/
utils
RSK World
music-classification
Music Classification Dataset - Genre Classification + Music AI + Audio ML
utils
  • __pycache__
  • __init__.py1.6 KB
  • advanced_features.py8.3 KB
  • audio_augmentation.py6.3 KB
  • audio_processor.py5.5 KB
  • feature_extractor.py6.7 KB
  • model_comparison.py8.8 KB
  • realtime_processor.py8.8 KB
audio_processor.py
utils/audio_processor.py
Raw Download
Find: Go to:
"""
Audio Processor Module for Music Classification

Project: Music Classification Dataset
Author: Molla Samser
Company: RSK World
Designer & Tester: Rima Khatun
Website: https://rskworld.in
Email: help@rskworld.in, support@rskworld.in
Phone: +91 93305 39277
Description: Audio processing utilities for loading and preprocessing music files
License: Educational Purpose Only
"""

import librosa
import numpy as np
import soundfile as sf
from typing import Tuple, Optional
import warnings
warnings.filterwarnings('ignore')


class AudioProcessor:
    """
    Audio processing class for music classification tasks
    
    Author: Molla Samser (RSK World)
    Website: https://rskworld.in
    """
    
    def __init__(self, sample_rate: int = 22050, duration: float = 30.0):
        """
        Initialize AudioProcessor
        
        Args:
            sample_rate: Target sample rate for audio files
            duration: Duration of audio clips in seconds
        """
        self.sample_rate = sample_rate
        self.duration = duration
        self.target_length = int(sample_rate * duration)
        
    def load_audio(self, file_path: str, offset: float = 0.0) -> np.ndarray:
        """
        Load audio file and return as numpy array
        
        Args:
            file_path: Path to audio file
            offset: Start reading after this time (in seconds)
            
        Returns:
            Audio time series as numpy array
        """
        try:
            audio, sr = librosa.load(
                file_path,
                sr=self.sample_rate,
                duration=self.duration,
                offset=offset
            )
            
            # Pad or trim to target length
            audio = self._pad_or_trim(audio)
            
            return audio
        except Exception as e:
            print(f"Error loading audio file {file_path}: {str(e)}")
            return np.zeros(self.target_length)
    
    def _pad_or_trim(self, audio: np.ndarray) -> np.ndarray:
        """
        Pad or trim audio to target length
        
        Args:
            audio: Input audio array
            
        Returns:
            Padded or trimmed audio array
        """
        if len(audio) > self.target_length:
            audio = audio[:self.target_length]
        elif len(audio) < self.target_length:
            padding = self.target_length - len(audio)
            audio = np.pad(audio, (0, padding), mode='constant')
        
        return audio
    
    def normalize_audio(self, audio: np.ndarray) -> np.ndarray:
        """
        Normalize audio amplitude
        
        Args:
            audio: Input audio array
            
        Returns:
            Normalized audio array
        """
        if np.max(np.abs(audio)) > 0:
            audio = audio / np.max(np.abs(audio))
        return audio
    
    def apply_noise_reduction(self, audio: np.ndarray, noise_factor: float = 0.005) -> np.ndarray:
        """
        Apply basic noise reduction
        
        Args:
            audio: Input audio array
            noise_factor: Noise reduction factor
            
        Returns:
            Audio with reduced noise
        """
        noise = np.random.randn(len(audio))
        audio_clean = audio - (noise * noise_factor)
        return audio_clean
    
    def get_audio_duration(self, file_path: str) -> float:
        """
        Get duration of audio file
        
        Args:
            file_path: Path to audio file
            
        Returns:
            Duration in seconds
        """
        try:
            duration = librosa.get_duration(path=file_path)
            return duration
        except Exception as e:
            print(f"Error getting duration for {file_path}: {str(e)}")
            return 0.0
    
    def convert_to_mono(self, audio: np.ndarray) -> np.ndarray:
        """
        Convert stereo audio to mono
        
        Args:
            audio: Input audio array (can be stereo or mono)
            
        Returns:
            Mono audio array
        """
        if audio.ndim > 1:
            audio = librosa.to_mono(audio)
        return audio
    
    def save_audio(self, audio: np.ndarray, file_path: str) -> bool:
        """
        Save audio array to file
        
        Args:
            audio: Audio array to save
            file_path: Output file path
            
        Returns:
            True if successful, False otherwise
        """
        try:
            sf.write(file_path, audio, self.sample_rate)
            return True
        except Exception as e:
            print(f"Error saving audio to {file_path}: {str(e)}")
            return False


# Example usage
if __name__ == "__main__":
    """
    Demo script for AudioProcessor
    
    Author: Molla Samser
    Company: RSK World
    Website: https://rskworld.in
    """
    processor = AudioProcessor()
    
    # Example audio file path
    audio_path = "../data/audio/classical/classical_001.wav"
    
    # Load audio
    print(f"Loading audio from: {audio_path}")
    audio = processor.load_audio(audio_path)
    print(f"Audio shape: {audio.shape}")
    print(f"Audio duration: {len(audio) / processor.sample_rate} seconds")
    
    # Normalize audio
    audio_normalized = processor.normalize_audio(audio)
    print(f"Audio normalized: min={np.min(audio_normalized):.4f}, max={np.max(audio_normalized):.4f}")

191 lines•5.5 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer