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
realtime_processor.py
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

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