### Integrate Audio Codecs with JavaScript Source: https://context7.com/johni0702/mumble-client/llms.txt Implements an interface for audio codecs like CELT and Opus, providing functions to get frame duration, create decoder streams, and create encoder streams. It relies on external modules for Opus encoding/decoding and Node.js stream functionality. ```javascript var myCodecs = { // Supported CELT versions (e.g., [0x8000000b]) celt: [], // Opus codec support opus: true, // Get duration of encoded frame without decoding getDuration: function (codec, buffer) { if (codec === 'Opus') { // Parse Opus packet header to determine duration // Must return milliseconds (multiple of 10) return 20 // 20ms frame } return 10 // Default }, // Create decoder stream for incoming audio createDecoderStream: function (user) { var Transform = require('stream').Transform var decoder = new Transform({ objectMode: true }) // Initialize decoder state for this user var opusDecoder = createOpusDecoder(48000, 1) decoder._transform = function (voiceData, encoding, callback) { // voiceData = { target, codec, frame, position } if (voiceData.codec === 'Opus') { var pcm = opusDecoder.decode(voiceData.frame) this.push({ target: voiceData.target, pcm: pcm, // Float32Array numberOfChannels: 1, position: voiceData.position }) } callback() } return decoder }, // Create encoder stream for outgoing audio createEncoderStream: function (codec) { var Transform = require('stream').Transform var encoder = new Transform({ objectMode: true }) // Initialize encoder state var opusEncoder = createOpusEncoder(48000, 1, 40000) // 48kHz, mono, 40kbps encoder._transform = function (pcmData, encoding, callback) { // pcmData = { target, pcm, numberOfChannels, position, bitrate } if (codec === 'Opus') { // Set encoder bitrate hint if provided if (pcmData.bitrate) { opusEncoder.setBitrate(pcmData.bitrate) } var encodedFrame = opusEncoder.encode(pcmData.pcm) this.push({ frame: encodedFrame, // Buffer position: pcmData.position }) } callback() } return encoder } } // Use codecs with client var client = new MumbleClient({ username: 'CodecUser', codecs: myCodecs }) // See mumble-client-codecs-node for Node.js implementation // See mumble-client-codecs-browser for browser implementation ``` -------------------------------- ### Initialize Mumble Client and Connect to Server (JavaScript) Source: https://context7.com/johni0702/mumble-client/llms.txt Initializes a Mumble client with provided credentials and connects to a server using a duplex data stream. It logs connection details, server information, and lists connected users and channels. This snippet demonstrates both callback-based and Promise-based connection APIs. ```javascript var MumbleClient = require('mumble-client') // Create client with authentication credentials var client = new MumbleClient({ username: 'MyBot', password: 'ServerPassword123', tokens: ['token1', 'token2'], codecs: myCodecImplementation, // See codec section below userVoiceTimeout: 200, dataPingInterval: 5000, maxInFlightDataPings: 2 }) // Connect using a duplex stream (provided by transport module) client.connectDataStream(someDuplexStream, function (err, connectedClient) { if (err) { console.error('Connection failed:', err) return } console.log('Connected to server') console.log('Welcome message:', connectedClient.welcomeMessage) console.log('Server version:', connectedClient.serverVersion) console.log('My username:', connectedClient.self.username) console.log('My channel:', connectedClient.self.channel.name) console.log('Max bandwidth:', connectedClient.maxBandwidth) // List all users connectedClient.users.forEach(function (user) { console.log('User:', user.username, 'in channel:', user.channel.name) }) // List all channels connectedClient.channels.forEach(function (channel) { console.log('Channel:', channel.name, 'with', channel.users.length, 'users') }) }) // Promise-based API is also available client.connectDataStream(someDuplexStream) .then(client => console.log('Connected')) .catch(err => console.error('Failed:', err)) ``` -------------------------------- ### Connect and Interact with Mumble Client Source: https://github.com/johni0702/mumble-client/blob/master/README.md Establishes a Mumble client connection, handles incoming voice data, and sends audio. It demonstrates connecting data and voice streams, managing user presence in channels, and processing received PCM audio frames. The module also supports sending audio by piping PCM data to an outgoing voice stream. ```javascript var MumbleClient = require('mumble-client') var client = new MumbleClient({ username: 'Test', password: 'Pass123' }) // someDuplexStream is used for data transmission and as a voice channel fallback client.connectDataStream(someDuplexStream, function (err, client) { if (err) throw err // Connection established console.log('Welcome message:', client.welcomeMessage) console.log('Actual username:', client.self.username) // Optionally connect a potentially lossy, udp-like voice channel client.connectVoiceStream(someOtherDuplexStream) var testChannel = client.getChannel('Test Channel') if (testChannel) { client.self.setChannel(testChannel) } client.users.forEach(function (user) { console.log('User', user.username, 'is in channel', user.channel.name) }) }) // You may then register listeners for the 'voice' event to receive a stream // of raw PCM frames. client.on('newUser', function (user) { user.on('voice', function (stream) { stream.on('data', function (data) { // Interleaved IEEE754 32-bit linear PCM with nominal range between -1 and +1 // May be of zero length which is usually only the case when voice.end is true console.log(data.pcm) // Float32Array console.log(data.numberOfChannels) // Target indicates who the user is talking to // Can be one of: 'normal', 'whisper', 'shout' console.log(data.target) // Neither numberOfChannels nor target should normally change during one // transmission however this cannot be guaranteed }).on('end', function () { // The current voice transmission has ended, stateful decoders have been reset // Can be used to disable the 'talking' indicator of this use // Because the last packet might get lost due to packet loss, a timer is // used to always fire this event. As a result a single transmission might // be split when packets are delayed. console.log(user.username, 'stopped talking.') }) }) }) // To send audio, pipe your raw PCM samples (as Float32Array or Buffer) at // 48kHz into an outgoing stream created with Client#createVoiceStream. // Any audio piped in the stream while muted, suppressed or not yet connected // will be silently dropped. // First argument is the target: 0 is normal talking, 1-31 are voice targets var voiceStream = client.createVoiceStream(0) myPcmSource.pipe(voiceStream) // Make sure the stream is ended when the transmission should end // For positional audio the Float32Array is wrapped in an object which // also contains the position: myPcmSource.on('data', function (chunk) { voiceStream.write({ pcm: chunk, x: 1, y: 2.5, z: 3 }) }) ``` -------------------------------- ### Handle Mumble Client Events with JavaScript Source: https://context7.com/johni0702/mumble-client/llms.txt This snippet illustrates how to set up event listeners for a Mumble client to manage connection states, handle incoming messages, respond to errors, and process permission denials. It covers connection events (connected, disconnected, reject), message events, permission denied events with various types, unknown codec events, and ping events for connection monitoring. It also shows how to access connection statistics and manually disconnect the client. ```javascript var client = new MumbleClient({ username: 'EventBot', codecs: myCodecs }) // Connection events client.on('connected', function () { console.log('Successfully connected to server') console.log('Session ID:', client.self.id) }) client.on('disconnected', function () { console.log('Disconnected from server') }) client.on('reject', function (rejectInfo) { console.error('Connection rejected by server:', rejectInfo) console.error('Type:', rejectInfo.type) console.error('Reason:', rejectInfo.reason) }) client.on('error', function (error) { console.error('Client error:', error) }) // Text message events client.on('message', function (sender, message, users, channels, trees) { console.log('Message from', sender.username + ':', message) console.log('Target users:', users.map(u => u.username)) console.log('Target channels:', channels.map(c => c.name)) console.log('Target trees:', trees.map(t => t.name)) }) // Permission denied events client.on('denied', function (type, user, channel, reason) { console.log('Permission denied:', type) if (user) console.log('User:', user.username) if (channel) console.log('Channel:', channel.name) if (reason) console.log('Reason:', reason) // Types: 'Text', 'Permission', 'SuperUser', 'ChannelName', 'TextTooLong', // 'TemporaryChannel', 'MissingCertificate', 'UserName', 'ChannelFull', 'NestingLimit' }) // Codec events client.on('unknown_codec', function (codecId) { console.warn('Received audio with unknown codec:', codecId) }) // Ping events for connection monitoring client.on('dataPing', function (duration) { console.log('Data channel ping:', duration, 'ms') }) // Check connection statistics var dataStats = client.dataStats if (dataStats) { console.log('Data packets:', dataStats.n) console.log('Average ping:', dataStats.mean, 'ms') console.log('Ping variance:', dataStats.variance) } var voiceStats = client.voiceStats if (voiceStats) { console.log('Voice packets:', voiceStats.n) console.log('Average ping:', voiceStats.mean, 'ms') } // Disconnect manually setTimeout(function () { client.disconnect() }, 60000) ``` -------------------------------- ### Manage Mumble Users and States with JavaScript Source: https://context7.com/johni0702/mumble-client/llms.txt This snippet demonstrates how to interact with users in a Mumble server using the Mumble client library. It covers iterating through users, retrieving specific users by ID, sending private messages, moving users to channels, managing mute/deafen states, registering users, clearing metadata, requesting full data, and managing self-state (mute, deafen, comment, texture, recording, plugin). It also includes event listeners for new users, user updates, and user removal. ```javascript client.connectDataStream(stream, function (err, client) { if (err) throw err // Iterate all users client.users.forEach(function (user) { console.log('User:', user.username) console.log('ID:', user.id) console.log('Unique ID:', user.uniqueId) console.log('Channel:', user.channel.name) console.log('Muted:', user.mute) console.log('Deafened:', user.deaf) console.log('Self-muted:', user.selfMute) console.log('Self-deafened:', user.selfDeaf) console.log('Suppressed:', user.suppress) console.log('Priority speaker:', user.prioritySpeaker) console.log('Recording:', user.recording) console.log('Comment:', user.comment) console.log('Texture hash:', user.textureHash) console.log('Cert hash:', user.certHash) }) // Get user by ID var specificUser = client.getUserById(3) if (specificUser) { // Send private message specificUser.sendMessage('Hello!') // Move user to channel (requires permissions) var lobby = client.getChannel('Lobby') specificUser.setChannel(lobby) // Mute/deafen user (requires permissions) specificUser.setMute(true) specificUser.setDeaf(true) // Register user (requires permissions) specificUser.register() // Clear user metadata specificUser.clearComment() specificUser.clearTexture() // Request full data specificUser.requestComment() specificUser.requestTexture() } // Manage self state client.setSelfMute(true) client.setSelfDeaf(false) client.setSelfComment('My status message') client.setSelfTexture(textureBuffer) client.setRecording(true) client.setPluginContext(contextBuffer) client.setPluginIdentity('my-app-v1.0') // Listen for user events client.on('newUser', function (user) { console.log('User connected:', user.username) }) specificUser.on('update', function (actor, changes) { console.log('User updated by', actor ? actor.username : 'server') console.log('Changes:', changes) }) specificUser.on('remove', function (actor, reason, ban) { console.log('User removed:', reason) console.log('Banned:', ban) if (actor) console.log('By:', actor.username) }) }) ``` -------------------------------- ### Manage Bandwidth with JavaScript Client Source: https://context7.com/johni0702/mumble-client/llms.txt Connects to the Mumble server and provides methods to control audio quality and manage bandwidth. It allows setting preferred audio quality (bitrate and packet size) and calculates various bitrate scenarios, including actual, preferred, and maximum possible bitrates, considering positional audio overhead and server limits. ```javascript client.connectDataStream(stream, function (err, client) { if (err) throw err console.log('Server max bandwidth:', client.maxBandwidth, 'bps') // Set preferred audio quality // samplesPerPacket: 480 (10ms), 960 (20ms), 1920 (40ms), 2880 (60ms) // bitrate: 8000-96000 bps client.setAudioQuality(40000, 960) // 40kbps, 20ms packets // Calculate actual bitrate (respects server limit) var actualBitrate = client.getActualBitrate(960, false) console.log('Actual bitrate:', actualBitrate, 'bps') // Calculate with positional audio overhead var actualBitrateWithPos = client.getActualBitrate(960, true) console.log('With position:', actualBitrateWithPos, 'bps') // Get preferred bitrate (before server limit) var preferred = client.getPreferredBitrate(960, false) console.log('Preferred bitrate:', preferred, 'bps') // Get maximum bitrate possible var max = client.getMaxBitrate(960, false) console.log('Max bitrate:', max, 'bps') // Calculate bandwidth for specific settings (static method) var bandwidth = MumbleClient.calcEnforcableBandwidth(40000, 960, false) console.log('Total bandwidth:', bandwidth, 'bps') // Create voice stream with quality settings var voiceStream = client.createVoiceStream(0, 1) // The stream will automatically use the configured quality settings }) ``` -------------------------------- ### Manage Mumble Channels Source: https://context7.com/johni0702/mumble-client/llms.txt Provides functionality to manage Mumble channels, including finding channels by name or ID, moving the client's user to a different channel, sending messages to channels or channel trees, and modifying channel properties like name, description, position, max users, and temporary status. It also covers moving channels to a new parent and listening for channel-related events. ```javascript client.connectDataStream(stream, function (err, client) { if (err) throw err // Find channel by name var targetChannel = client.getChannel('General') if (targetChannel) { console.log('Found channel:', targetChannel.name) console.log('Channel ID:', targetChannel.id) console.log('Users in channel:', targetChannel.users.length) console.log('Description:', targetChannel.description) console.log('Parent:', targetChannel.parent ? targetChannel.parent.name : 'root') console.log('Children:', targetChannel.children.map(c => c.name)) console.log('Max users:', targetChannel.maxUsers) console.log('Temporary:', targetChannel.temporary) // Move self to channel client.self.setChannel(targetChannel) // Send message to channel targetChannel.sendMessage('Hello everyone!') // Send message to channel tree (channel + all subchannels) targetChannel.sendTreeMessage('Broadcast to all subchannels') // Modify channel properties (requires permissions) targetChannel.setName('New Channel Name') targetChannel.setDescription('Updated description') targetChannel.setPosition(5) targetChannel.setMaxUsers(10) targetChannel.setTemporary(true) // Move channel to different parent var newParent = client.getChannel('Parent Channel') if (newParent) { targetChannel.setParent(newParent) } // Request full description (if only hash is available) targetChannel.requestDescription() } // Access root channel var rootChannel = client.root console.log('Root channel:', rootChannel.name) // Get channel by ID var channelById = client.getChannelById(5) // Listen for channel events client.on('newChannel', function (channel) { console.log('Channel created:', channel.name) }) targetChannel.on('update', function (changes) { console.log('Channel updated:', changes) }) targetChannel.on('remove', function () { console.log('Channel removed') }) }) ``` -------------------------------- ### Connect Voice Channel for Low Latency Audio (JavaScript) Source: https://context7.com/johni0702/mumble-client/llms.txt Establishes a connection to a separate voice channel, typically UDP-based, for lower latency audio transmission. If a dedicated voice stream is not connected, audio data will be tunneled through the main data stream. Requires a MumbleClient instance and a duplex stream for the voice channel. ```javascript var client = new MumbleClient({ username: 'VoiceBot', codecs: myCodecs }) client.connectDataStream(tcpStream, function (err, client) { if (err) throw err // Optionally connect a separate voice stream (UDP-based, potentially lossy) // If not connected, voice data will be tunneled through the data stream client.connectVoiceStream(udpStream) console.log('Voice channel connected') console.log('Audio will use dedicated UDP channel when available') }) ``` -------------------------------- ### Receive and Process Voice Data Streams (JavaScript) Source: https://context7.com/johni0702/mumble-client/llms.txt Listens for voice transmissions from other users and processes the incoming audio streams. It handles 'newUser' events and listens for 'voice' events emitted by each user. The voice stream provides raw PCM audio data, including details about channels, target volume, and positional audio if available. Requires a MumbleClient instance and a data stream connection. ```javascript var MumbleClient = require('mumble-client') var client = new MumbleClient({ username: 'Listener', codecs: myCodecs }) client.connectDataStream(stream, function (err) { if (err) throw err // Listen for new users joining client.on('newUser', function (user) { console.log('New user joined:', user.username) // Each user emits 'voice' events when they start speaking user.on('voice', function (voiceStream) { console.log(user.username, 'started talking') // Voice stream emits PCM audio data voiceStream.on('data', function (audioData) { // Process raw PCM audio console.log('PCM samples:', audioData.pcm) // Float32Array console.log('Channels:', audioData.numberOfChannels) // Usually 1 (mono) or 2 (stereo) console.log('Target:', audioData.target) // 'normal', 'whisper', or 'shout' // Positional audio (if available) if (audioData.position) { console.log('Position:', audioData.position.x, audioData.position.y, audioData.position.z) } // Play audio, save to file, analyze, etc. // PCM is Float32Array with interleaved IEEE754 32-bit samples in [-1, 1] myAudioPlayer.write(audioData.pcm) }) voiceStream.on('end', function () { console.log(user.username, 'stopped talking') // Hide "talking" indicator, reset state, etc. }) }) }) }) ``` -------------------------------- ### Send Voice Data to Mumble Server Source: https://context7.com/johni0702/mumble-client/llms.txt Establishes an outgoing voice stream and transmits audio data to the Mumble server. It allows setting audio quality, creating voice streams for different targets, sending PCM audio in various formats (Float32Array, Buffer, positional audio objects), and streaming from a source. The transmission can be ended manually after a specified duration. Requires a MumbleClient instance and codec information. ```javascript var client = new MumbleClient({ username: 'Speaker', codecs: myCodecs }) client.connectDataStream(stream, function (err, client) { if (err) throw err // Set audio quality preferences (bitrate and samples per packet) // Bitrate: 8000-96000 bits/sec, samples: 480 (10ms), 960 (20ms), 1920 (40ms), 2880 (60ms) client.setAudioQuality(40000, 960) // 40kbps, 20ms packets // Create voice stream (target 0 = normal talking, 1-31 = voice targets) var voiceStream = client.createVoiceStream(0, 1) // target 0, mono // Send PCM audio at 48kHz sample rate // Input can be Float32Array or Buffer var pcmBuffer = new Float32Array(960) // 20ms of mono audio at 48kHz // Fill buffer with audio samples... for (var i = 0; i < pcmBuffer.length; i++) { pcmBuffer[i] = Math.sin(2 * Math.PI * 440 * i / 48000) // 440 Hz tone } voiceStream.write(pcmBuffer) // For positional audio, wrap PCM in an object with position voiceStream.write({ pcm: pcmBuffer, x: 10.5, y: 0.0, z: -5.3 }) // Stream from a source myPcmSource.on('data', function (chunk) { voiceStream.write(chunk) }) // Important: end the stream when transmission should stop setTimeout(function () { voiceStream.end() console.log('Voice transmission ended') }, 5000) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.