🔍 Code Extractor

class SoundPlayer

Maturity: 56

A Panel ReactiveHTML component that provides audio feedback for TxConnect application, with configurable sound modes and multiple sound types for different events.

File:
/tf/active/vicechatdev/resources/py2html.py
Lines:
652 - 729
Complexity:
moderate

Purpose

SoundPlayer is a UI component that manages audio feedback in the TxConnect application. It provides visual controls (volume icon) and plays different sounds based on events (errors, success, notifications). The component supports three modes: 'Mute' (no sounds), 'Error' (only error sounds), and 'All' (all sounds). It integrates JavaScript for client-side audio playback and uses Panel's reactive framework to trigger sounds from Python code.

Source Code

class SoundPlayer(ReactiveHTML):
    """
    Sound feedback for TxConnect.
    
    
    attributes
    ----------
    mode : param.Selector
        The sound play mode, 'Mute' to play nothing, 'Error' for only errors, and 'All' for all sounds.
    sound_type : param.String
        The current sound type to play when the function gets called
    value : param.Integer
        Changes in value triggers the audio queue
    """
    mode = param.Selector(default='All', objects=["Mute","Error","All"])
    sound_type = param.String()
    value = param.Integer(default=0)
    notification = param.Integer(default=0)
    
    _template = """
    <i id="audio" href="#" class="fa fa-volume-up" notification="${notification}" value="${value}" onclick="${script('on_click')}" aria-hidden="true" style="font-size:20px"></i>
    """
    
    _scripts = {
        "after_layout":
        """
            if (data.mode === "Mute") {
                audio.classList.remove('fa-volume-up');
                audio.classList.add('fa-volume-off');
            } else if (data.mode ==="Error") {
                audio.classList.remove('fa-volume-up');
                audio.classList.add('fa-volume-down');
            };
        """,
        "on_click":
        """
            if (audio.classList.contains('fa-volume-up')) {
                audio.classList.remove('fa-volume-up');
                audio.classList.add('fa-volume-off');
                data.mode = "Mute"
            } else if (audio.classList.contains('fa-volume-off')) {
                audio.classList.remove('fa-volume-off');
                audio.classList.add('fa-volume-down');
                data.mode = "Error"
            } else {
                audio.classList.remove('fa-volume-down');
                audio.classList.add('fa-volume-up');
                data.mode = "All"
            };
        """,
        "value":
        """
            var audio_error = new Audio('./custom_static/sound/quack.mp3');
            var audio_success = new Audio('./custom_static/sound/success.mp3');
            if (data.sound_type === "Error" && (data.mode === "Error" || data.mode === "All")) {
                audio_error.play();
            } else if (data.mode === "All") {
                audio_success.play();
            }
        """,
        "notification":
        """
            var mail = new Audio('./custom_static/sound/mail.wav');
            if (data.mode === "Error" || data.mode === "All") {
                mail.play();
            }
        """,
    }
        
    def trigger_sound(self, sound_type='Error'):
        """
        Call this function to trigger the front-end to play a sound of given sound_type. 
        """
        self.sound_type = sound_type
        self.value += 1
        
    def notify(self):
        self.notification += 1

Parameters

Name Type Default Kind
bases ReactiveHTML -

Parameter Details

mode: A param.Selector that controls the sound playback mode. Default is 'All'. Options are: 'Mute' (no sounds played), 'Error' (only error sounds played), 'All' (all sounds including success and notifications played). Changes to this parameter update the UI icon.

sound_type: A param.String that specifies the type of sound to play when trigger_sound() is called. Typically 'Error' for error sounds or other values for success sounds. This is set internally by trigger_sound() method.

value: A param.Integer counter that triggers the audio playback when incremented. Default is 0. Each increment triggers the JavaScript 'value' script to play the appropriate sound based on sound_type and mode.

notification: A param.Integer counter that triggers notification sound playback when incremented. Default is 0. Each increment triggers the JavaScript 'notification' script to play a mail notification sound.

Return Value

Instantiation returns a SoundPlayer object that inherits from ReactiveHTML. The trigger_sound() method returns None (implicitly). The notify() method returns None (implicitly). Both methods have side effects of playing audio through JavaScript.

Class Interface

Methods

trigger_sound(sound_type: str = 'Error') -> None

Purpose: Triggers audio playback on the frontend by setting the sound type and incrementing the value counter

Parameters:

  • sound_type: The type of sound to play. Default is 'Error'. 'Error' plays quack.mp3, any other value plays success.mp3 (when mode allows)

Returns: None. Side effect: plays audio in browser based on current mode setting

notify() -> None

Purpose: Triggers a notification sound (mail.wav) by incrementing the notification counter

Returns: None. Side effect: plays notification sound in browser if mode is 'Error' or 'All'

Attributes

Name Type Description Scope
mode param.Selector Controls which sounds are played. Options: 'Mute' (no sounds), 'Error' (errors and notifications only), 'All' (all sounds). Default is 'All' class
sound_type param.String Stores the current sound type to be played. Set by trigger_sound() method. 'Error' plays error sound, other values play success sound class
value param.Integer Counter that triggers audio playback when incremented. Default is 0. Watched by JavaScript to play sounds based on sound_type and mode class
notification param.Integer Counter that triggers notification sound playback when incremented. Default is 0. Watched by JavaScript to play mail notification sound class
_template str HTML template string defining the component's DOM structure. Renders as a clickable volume icon with Font Awesome classes class
_scripts dict Dictionary of JavaScript code snippets that handle UI updates and audio playback. Keys: 'after_layout', 'on_click', 'value', 'notification' class

Dependencies

  • param
  • panel
  • panel.reactive.ReactiveHTML

Required Imports

import param
import panel as pn
from panel.reactive import ReactiveHTML

Usage Example

import param
import panel as pn
from panel.reactive import ReactiveHTML

class SoundPlayer(ReactiveHTML):
    # ... (class definition as provided)
    pass

# Instantiate the sound player
sound_player = SoundPlayer(mode='All')

# Add to a Panel layout
app = pn.Column(sound_player)

# Trigger an error sound
sound_player.trigger_sound(sound_type='Error')

# Trigger a success sound
sound_player.trigger_sound(sound_type='Success')

# Trigger a notification
sound_player.notify()

# Change mode programmatically
sound_player.mode = 'Error'  # Only play error sounds
sound_player.mode = 'Mute'   # Mute all sounds

# Serve the app
app.servable()

Best Practices

  • Ensure audio files exist at the specified paths before instantiating the component
  • Use trigger_sound() method to play sounds from Python code rather than directly modifying value parameter
  • The value and notification parameters are counters - they should only be incremented, not set to specific values
  • The component requires a running Panel server to function properly as it relies on JavaScript execution
  • Users can click the volume icon to cycle through modes: All -> Mute -> Error -> All
  • The sound_type parameter is typically set internally by trigger_sound() and should not be modified directly
  • Mode changes affect which sounds are played: 'Mute' plays nothing, 'Error' plays only errors and notifications, 'All' plays everything
  • The component is stateful - mode changes persist across sound triggers
  • Audio playback happens client-side in the browser, so network latency does not affect sound timing

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class Browser_button 45.0% similar

    A custom Panel ReactiveHTML button component that displays a file or folder icon with text and tracks click events.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class Confirm_button 44.5% similar

    A custom Panel button widget that conditionally displays a confirmation dialog before registering clicks, built on ReactiveHTML with integrated JavaScript handlers.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class Focus_button 43.2% similar

    A custom Panel ReactiveHTML button widget that displays an eye icon and tracks the number of times it has been clicked.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class Toggle_switch 41.8% similar

    A customizable toggle switch widget in C-Path style that extends ReactiveHTML, providing a checkbox-like interface with visual slider representation.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class BaseUIComponent 41.4% similar

    Base class for UI components that provides common notification functionality for displaying error, success, warning, and info messages.

    From: /tf/active/vicechatdev/CDocs/ui/base_ui.py
← Back to Browse