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
data_exploration.pyaudio_processor.pyrealtime_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
utils/realtime_processor.py
Raw Download
Find: Go to:
"""
Real-Time Audio Processing 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: Real-time audio processing and classification
License: Educational Purpose Only
"""

import numpy as np
import queue
import threading
import time
from typing import Callable
import warnings
warnings.filterwarnings('ignore')


class RealtimeAudioProcessor:
    """
    Real-time audio processing and classification
    
    Author: Molla Samser (RSK World)
    Website: https://rskworld.in
    Email: help@rskworld.in
    Phone: +91 93305 39277
    """
    
    def __init__(self, sample_rate=22050, chunk_duration=2.0):
        """
        Initialize Real-time Audio Processor
        
        Args:
            sample_rate: Audio sample rate
            chunk_duration: Duration of audio chunks in seconds
        """
        self.sample_rate = sample_rate
        self.chunk_duration = chunk_duration
        self.chunk_size = int(sample_rate * chunk_duration)
        self.audio_queue = queue.Queue()
        self.result_queue = queue.Queue()
        self.is_running = False
        self.processing_thread = None
    
    def start_processing(self, process_func: Callable):
        """
        Start real-time processing
        
        Args:
            process_func: Function to process audio chunks
        """
        self.is_running = True
        self.processing_thread = threading.Thread(
            target=self._processing_loop,
            args=(process_func,)
        )
        self.processing_thread.start()
        print("Real-time processing started...")
        print("Author: Molla Samser | RSK World")
    
    def stop_processing(self):
        """Stop real-time processing"""
        self.is_running = False
        if self.processing_thread:
            self.processing_thread.join()
        print("Real-time processing stopped.")
    
    def _processing_loop(self, process_func: Callable):
        """Main processing loop"""
        while self.is_running:
            try:
                # Get audio chunk from queue
                audio_chunk = self.audio_queue.get(timeout=0.1)
                
                # Process chunk
                result = process_func(audio_chunk)
                
                # Put result in queue
                self.result_queue.put({
                    'timestamp': time.time(),
                    'result': result
                })
                
            except queue.Empty:
                continue
            except Exception as e:
                print(f"Error in processing: {str(e)}")
    
    def add_audio_chunk(self, audio_chunk: np.ndarray):
        """
        Add audio chunk for processing
        
        Args:
            audio_chunk: Audio data chunk
        """
        self.audio_queue.put(audio_chunk)
    
    def get_result(self, timeout=None):
        """
        Get processing result
        
        Args:
            timeout: Timeout in seconds
            
        Returns:
            Processing result or None
        """
        try:
            return self.result_queue.get(timeout=timeout)
        except queue.Empty:
            return None
    
    def process_stream(self, audio_stream, process_func: Callable, duration=None):
        """
        Process audio stream
        
        Args:
            audio_stream: Iterator yielding audio chunks
            process_func: Function to process audio
            duration: Duration to process (None for infinite)
        """
        self.start_processing(process_func)
        
        start_time = time.time()
        chunk_count = 0
        
        try:
            for audio_chunk in audio_stream:
                if duration and (time.time() - start_time) > duration:
                    break
                
                self.add_audio_chunk(audio_chunk)
                chunk_count += 1
                
                # Get and display result
                result = self.get_result(timeout=0.1)
                if result:
                    print(f"Chunk {chunk_count}: {result['result']}")
        
        finally:
            self.stop_processing()


class StreamingBuffer:
    """
    Streaming audio buffer for continuous processing
    
    Author: Molla Samser (RSK World)
    Website: https://rskworld.in
    """
    
    def __init__(self, buffer_size=44100):
        """
        Initialize Streaming Buffer
        
        Args:
            buffer_size: Size of circular buffer
        """
        self.buffer_size = buffer_size
        self.buffer = np.zeros(buffer_size)
        self.write_pos = 0
        self.lock = threading.Lock()
    
    def write(self, data: np.ndarray):
        """
        Write data to buffer
        
        Args:
            data: Audio data to write
        """
        with self.lock:
            data_len = len(data)
            end_pos = self.write_pos + data_len
            
            if end_pos <= self.buffer_size:
                self.buffer[self.write_pos:end_pos] = data
            else:
                # Wrap around
                first_part = self.buffer_size - self.write_pos
                self.buffer[self.write_pos:] = data[:first_part]
                self.buffer[:data_len - first_part] = data[first_part:]
            
            self.write_pos = end_pos % self.buffer_size
    
    def read(self, size: int) -> np.ndarray:
        """
        Read data from buffer
        
        Args:
            size: Number of samples to read
            
        Returns:
            Audio data
        """
        with self.lock:
            read_pos = (self.write_pos - size) % self.buffer_size
            
            if read_pos + size <= self.buffer_size:
                return self.buffer[read_pos:read_pos + size].copy()
            else:
                # Wrap around
                first_part = self.buffer_size - read_pos
                result = np.concatenate([
                    self.buffer[read_pos:],
                    self.buffer[:size - first_part]
                ])
                return result
    
    def get_latest(self, size: int) -> np.ndarray:
        """Get latest audio from buffer"""
        return self.read(size)


class FeatureCache:
    """
    Cache for extracted features
    
    Author: Molla Samser (RSK World)
    """
    
    def __init__(self, max_size=100):
        """
        Initialize Feature Cache
        
        Args:
            max_size: Maximum number of cached items
        """
        self.cache = {}
        self.max_size = max_size
        self.access_order = []
    
    def set(self, key: str, value):
        """Add item to cache"""
        if key in self.cache:
            self.access_order.remove(key)
        
        self.cache[key] = value
        self.access_order.append(key)
        
        # Remove oldest if cache is full
        if len(self.cache) > self.max_size:
            oldest_key = self.access_order.pop(0)
            del self.cache[oldest_key]
    
    def get(self, key: str):
        """Get item from cache"""
        if key in self.cache:
            # Move to end (most recently used)
            self.access_order.remove(key)
            self.access_order.append(key)
            return self.cache[key]
        return None
    
    def clear(self):
        """Clear cache"""
        self.cache.clear()
        self.access_order.clear()


# Example usage
if __name__ == "__main__":
    """
    Demo script for Real-time Audio Processor
    
    Author: Molla Samser
    Company: RSK World
    Website: https://rskworld.in
    """
    print("Real-Time Audio Processing")
    print("Author: Molla Samser | RSK World")
    print("Website: https://rskworld.in")
    print("\nFeatures:")
    print("- Real-time audio processing")
    print("- Streaming buffer management")
    print("- Feature caching")
    print("- Multi-threaded processing")
    
    # Demo processing function
    def demo_process(audio_chunk):
        """Demo processing function"""
        return {
            'mean': np.mean(audio_chunk),
            'std': np.std(audio_chunk),
            'max': np.max(audio_chunk)
        }
    
    # Create processor
    processor = RealtimeAudioProcessor()
    
    # Create demo audio stream
    def demo_stream():
        for i in range(5):
            yield np.random.randn(44100)
            time.sleep(0.5)
    
    print("\nProcessing demo stream...")
    processor.process_stream(demo_stream(), demo_process, duration=3)
    
    print("\n© 2026 RSK World - Molla Samser")

306 lines•8.8 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

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