local Players = game:GetService("Players") local SoundService = game:GetService("SoundService") local TeleportService = game:GetService("TeleportService") local HttpService = game:GetService("HttpService") local LocalPlayer = Players.LocalPlayer if not LocalPlayer then error("REX SoundService must be executed in a client context.") end -- Official Rayfield loader (Sirius). local Rayfield local loaded, loadError = pcall(function() Rayfield = loadstring(game:HttpGet("https://sirius.menu/rayfield"))() end) if not loaded or not Rayfield then error("Rayfield could not be loaded: " .. tostring(loadError)) end local TEXT = { en = { welcome = "Welcome to REX SoundService", language = "Language", chooseLanguage = "Select a language to open the interface.", warningTitle = "SERVER-SIDE AUDIO NOTICE", warning1 = "For server-side audio replication, SoundService.RespectFilteringEnabled must be FALSE.", warning2 = "If it is TRUE, audio started by this client will only be heard locally. This script does not change that setting.", warning3 = "SERVER mode plays the original Sound instance. CLIENT mode plays a local clone.", accept = "Accept and continue", browser = "Sound Browser", playback = "Playback", scan = "Start / rescan (about 1 minute)", scanning = "Scanning game sounds... %d%%", scanDone = "Scan complete. Found %d sounds.", scanEmpty = "The scan finished, but no usable sounds were found.", scanBusy = "A scan is already running.", sounds = "Available sounds", selection = "Selection", none = "None", one = "One", various = "Several", selectedCount = "Selected sounds: %d", clear = "Clear selection", copy = "Copy selected audio IDs", mode = "Playback mode", client = "Client", server = "Server", loop = "Loop", playbackType = "Playback order", all = "All at once", oneByOne = "One by one", inject = "Play audio", stop = "Stop", status = "Status", filteringTrue = "True", filteringFalse = "False", filteringUnknown = "Unavailable", filteringStatus = "RespectFilteringEnabled: %s", filteringTrueInfo = "When true, sounds started by this client may stay local.", filteringFalseInfo = "When false, the experience may allow server-side sound replication.", currentMode = "Current playback mode: %s", statusExplanation = "Server playback uses the original Sound instance. Client playback uses a local clone. This script does not change game settings.", idle = "Ready.", nothingSelected = "Select at least one sound first.", started = "Playback started.", stopped = "Playback stopped.", finished = "Playback finished.", serverWarning = "RespectFilteringEnabled is TRUE. Server replication is not enabled; audio may remain client-only.", serverReady = "RespectFilteringEnabled is FALSE. Server replication may be allowed by the experience.", filterUnknown = "RespectFilteringEnabled could not be read.", copied = "Sound ID copied.", clipboardUnavailable = "Clipboard is unavailable. Sound ID: %s", shownLimit = "Showing the first %d sounds to keep the interface responsive.", tabInfo = "Select sounds here. Click an already-selected entry again to deselect it.", serverModeInfo = "Server mode uses the original Sound instance. Replication depends on the experience's RespectFilteringEnabled setting.", clientModeInfo = "Client creates and plays a local clone. Other players will not hear it.", stay = "Stay in the game", leave = "Leave the game", leaveMessage = "Leaving because RespectFilteringEnabled is true.", filterWarningTitle = "Server audio will not replicate", filterWarningBody = "RespectFilteringEnabled is true. Server mode will not work as intended in this experience.", rejoin = "Teleporter", randomServer = "Join a random server", teleporting = "Teleporting...", teleportFailed = "Teleport failed: %s", randomServerFailed = "Could not find or join another public server.", randomServerSearching = "Searching for a public server...", scan = "Rescan sounds", languageNames = {"English", "Español", "Português", "한국어", "中文", "Русский"} }, es = { welcome = "Bienvenido a REX SoundService", language = "Idioma", chooseLanguage = "Selecciona un idioma para abrir la interfaz.", warningTitle = "AVISO DE AUDIO SERVER-SIDE", warning1 = "Para replicar el audio mediante el servidor, SoundService.RespectFilteringEnabled debe estar en FALSE.", warning2 = "Si está en TRUE, el audio iniciado por este cliente solo se escuchará localmente. Este script no modifica esa configuración.", warning3 = "El modo SERVER reproduce el objeto Sound original. El modo CLIENT reproduce un clon local.", accept = "Aceptar y continuar", browser = "Explorador de sonidos", playback = "Reproducción", scan = "Iniciar / repetir escaneo (aprox. 1 minuto)", scanning = "Escaneando sonidos del juego... %d%%", scanDone = "Escaneo completado. Se encontraron %d sonidos.", scanEmpty = "El escaneo terminó, pero no se encontraron sonidos válidos.", scanBusy = "Ya hay un escaneo en curso.", sounds = "Sonidos disponibles", selection = "Selección", none = "Ninguno", one = "Uno", various = "Varios", selectedCount = "Sonidos seleccionados: %d", clear = "Limpiar selección", copy = "Copiar los ID de los audios seleccionados", mode = "Modo de reproducción", client = "Cliente", server = "Servidor", loop = "Bucle", playbackType = "Orden de reproducción", all = "Todos a la vez", oneByOne = "Uno por uno", inject = "Reproducir audio", stop = "Detener", status = "Estado", filteringTrue = "Activado (true)", filteringFalse = "Desactivado (false)", filteringUnknown = "No disponible", filteringStatus = "RespectFilteringEnabled: %s", filteringTrueInfo = "Si está en true, los sonidos iniciados por este cliente pueden quedarse en local.", filteringFalseInfo = "Si está en false, la experiencia puede permitir la replicación del audio mediante el servidor.", currentMode = "Modo de reproducción actual: %s", statusExplanation = "La reproducción en Server usa el objeto Sound original. Client utiliza un clon local. Este script no modifica la configuración del juego.", idle = "Preparado.", nothingSelected = "Selecciona al menos un sonido primero.", started = "Reproducción iniciada.", stopped = "Reproducción detenida.", finished = "Reproducción finalizada.", serverWarning = "RespectFilteringEnabled está en TRUE. La replicación del servidor no está habilitada; el audio puede quedarse solo en el cliente.", serverReady = "RespectFilteringEnabled está en FALSE. La experiencia puede permitir la replicación del servidor.", filterUnknown = "No se pudo leer RespectFilteringEnabled.", copied = "ID del sonido copiado.", clipboardUnavailable = "Portapapeles no disponible. ID del sonido: %s", shownLimit = "Se muestran los primeros %d sonidos para mantener la interfaz fluida.", tabInfo = "Selecciona sonidos aquí. Pulsa de nuevo una entrada seleccionada para deseleccionarla.", serverModeInfo = "Server utiliza el objeto Sound original. La replicación depende de RespectFilteringEnabled en la experiencia.", clientModeInfo = "Client crea y reproduce un clon local. Los demás jugadores no lo escucharán.", stay = "Permanecer en el juego", leave = "Salir del juego", leaveMessage = "Saliendo porque RespectFilteringEnabled está activado.", filterWarningTitle = "El audio del servidor no se replicará", filterWarningBody = "RespectFilteringEnabled está en true. El modo Server no funcionará correctamente en esta experiencia.", rejoin = "Teletransportador", randomServer = "Entrar en un servidor aleatorio", teleporting = "Teletransportando...", teleportFailed = "Error al teletransportar: %s", randomServerFailed = "No se pudo encontrar o entrar en otro servidor público.", randomServerSearching = "Buscando un servidor público...", scan = "Volver a escanear sonidos", languageNames = {"English", "Español", "Português", "한국어", "中文", "Русский"} }, pt = { welcome = "Bem-vindo ao REX SoundService", language = "Idioma", chooseLanguage = "Escolha um idioma para abrir a interface.", warningTitle = "AVISO DE ÁUDIO SERVER-SIDE", warning1 = "Para replicar o áudio pelo servidor, SoundService.RespectFilteringEnabled deve estar em FALSE.", warning2 = "Se estiver em TRUE, o áudio iniciado por este cliente será ouvido apenas localmente. Este script não altera essa configuração.", warning3 = "O modo SERVER reproduz o objeto Sound original. O modo CLIENT reproduz uma cópia local.", accept = "Aceitar e continuar", browser = "Lista de sons", playback = "Reprodução", scan = "Iniciar / repetir pesquisa (aprox. 1 minuto)", scanning = "Pesquisando sons do jogo... %d%%", scanDone = "Pesquisa concluída. %d sons encontrados.", scanEmpty = "A pesquisa terminou, mas nenhum som válido foi encontrado.", scanBusy = "Já existe uma pesquisa em andamento.", sounds = "Sons disponíveis", selection = "Seleção", none = "Nenhum", one = "Um", various = "Vários", selectedCount = "Sons selecionados: %d", clear = "Limpar seleção", copy = "Copiar os IDs dos sons selecionados", mode = "Modo de reprodução", client = "Cliente", server = "Servidor", loop = "Repetir", playbackType = "Ordem de reprodução", all = "Todos ao mesmo tempo", oneByOne = "Um por um", inject = "Reproduzir áudio", stop = "Parar", status = "Estado", filteringTrue = "Ativado (true)", filteringFalse = "Desativado (false)", filteringUnknown = "Indisponível", filteringStatus = "RespectFilteringEnabled: %s", filteringTrueInfo = "Se estiver em true, os sons iniciados por este cliente podem ficar apenas locais.", filteringFalseInfo = "Se estiver em false, a experiência pode permitir a replicação de áudio pelo servidor.", currentMode = "Modo de reprodução atual: %s", statusExplanation = "A reprodução em Server usa o objeto Sound original. Client utiliza uma cópia local. Este script não altera as configurações do jogo.", idle = "Pronto.", nothingSelected = "Selecione pelo menos um som primeiro.", started = "Reprodução iniciada.", stopped = "Reprodução parada.", finished = "Reprodução concluída.", serverWarning = "RespectFilteringEnabled está em TRUE. A replicação do servidor não está habilitada; o áudio pode ficar apenas no cliente.", serverReady = "RespectFilteringEnabled está em FALSE. A experiência pode permitir a replicação pelo servidor.", filterUnknown = "Não foi possível ler RespectFilteringEnabled.", copied = "ID do som copiado.", clipboardUnavailable = "Área de transferência indisponível. ID do som: %s", shownLimit = "Mostrando os primeiros %d sons para manter a interface responsiva.", tabInfo = "Selecione sons aqui. Clique novamente em um item selecionado para removê-lo da seleção.", serverModeInfo = "Server usa o objeto Sound original. A replicação depende de RespectFilteringEnabled na experiência.", clientModeInfo = "Client cria e reproduz uma cópia local. Os outros jogadores não ouvirão.", stay = "Permanecer no jogo", leave = "Sair do jogo", leaveMessage = "Saindo porque RespectFilteringEnabled está ativado.", filterWarningTitle = "O áudio do servidor não será replicado", filterWarningBody = "RespectFilteringEnabled está true. O modo Server não funcionará corretamente nesta experiência.", rejoin = "Teletransportador", randomServer = "Entrar em um servidor aleatório", teleporting = "Teleportando...", teleportFailed = "Falha no teletransporte: %s", randomServerFailed = "Não foi possível encontrar ou entrar em outro servidor público.", randomServerSearching = "Procurando um servidor público...", scan = "Pesquisar sons novamente", languageNames = {"English", "Español", "Português", "한국어", "中文", "Русский"} }, ko = { welcome = "REX SoundService에 오신 것을 환영합니다", language = "언어", chooseLanguage = "언어를 선택하면 인터페이스가 열립니다.", warningTitle = "서버 오디오 복제 안내", warning1 = "서버를 통해 오디오를 복제하려면 SoundService.RespectFilteringEnabled가 FALSE여야 합니다.", warning2 = "TRUE이면 이 클라이언트에서 시작한 오디오는 로컬에서만 들립니다. 이 스크립트는 해당 설정을 변경하지 않습니다.", warning3 = "Server 모드는 원본 Sound 인스턴스를 재생합니다. Client 모드는 로컬 복제본을 재생합니다.", accept = "동의하고 계속", browser = "사운드 브라우저", playback = "재생", scan = "검색 시작 / 다시 검색 (약 1분)", scanning = "게임 사운드 검색 중... %d%%", scanDone = "검색 완료. 사운드 %d개를 찾았습니다.", scanEmpty = "검색이 끝났지만 사용할 수 있는 사운드를 찾지 못했습니다.", scanBusy = "이미 검색이 진행 중입니다.", sounds = "사용 가능한 사운드", selection = "선택", none = "없음", one = "하나", various = "여러 개", selectedCount = "선택한 사운드: %d개", clear = "선택 지우기", copy = "선택한 사운드 ID 복사", mode = "재생 모드", client = "클라이언트", server = "서버", loop = "반복", playbackType = "재생 순서", all = "모두 동시에", oneByOne = "하나씩", inject = "오디오 재생", stop = "중지", status = "상태", filteringTrue = "켜짐 (true)", filteringFalse = "꺼짐 (false)", filteringUnknown = "확인할 수 없음", filteringStatus = "RespectFilteringEnabled: %s", filteringTrueInfo = "true이면 이 클라이언트에서 시작한 사운드가 로컬에서만 재생될 수 있습니다.", filteringFalseInfo = "false이면 경험 설정에 따라 서버 오디오 복제가 허용될 수 있습니다.", currentMode = "현재 재생 모드: %s", statusExplanation = "Server 재생은 원본 Sound 인스턴스를 사용합니다. Client 재생은 로컬 복제본을 사용합니다. 이 스크립트는 게임 설정을 변경하지 않습니다.", idle = "준비 완료.", nothingSelected = "먼저 사운드를 하나 이상 선택하세요.", started = "재생을 시작했습니다.", stopped = "재생을 중지했습니다.", finished = "재생이 완료되었습니다.", serverWarning = "RespectFilteringEnabled가 TRUE입니다. 서버 복제가 활성화되지 않아 오디오가 클라이언트에서만 들릴 수 있습니다.", serverReady = "RespectFilteringEnabled가 FALSE입니다. 경험 설정에 따라 서버 복제가 허용될 수 있습니다.", filterUnknown = "RespectFilteringEnabled 값을 읽을 수 없습니다.", copied = "사운드 ID를 복사했습니다.", clipboardUnavailable = "클립보드를 사용할 수 없습니다. 사운드 ID: %s", shownLimit = "인터페이스 응답성을 위해 처음 %d개의 사운드만 표시합니다.", tabInfo = "여기에서 사운드를 선택하세요. 이미 선택한 항목을 다시 누르면 선택이 해제됩니다.", serverModeInfo = "SERVER는 원본 Sound 인스턴스를 사용합니다. 복제 여부는 경험의 RespectFilteringEnabled 설정에 따라 달라집니다.", clientModeInfo = "CLIENT는 로컬 복제본을 만들어 재생합니다. 다른 플레이어에게는 들리지 않습니다.", stay = "게임에 남아 있기", leave = "게임 나가기", leaveMessage = "RespectFilteringEnabled가 켜져 있어 게임을 나갑니다.", filterWarningTitle = "서버 오디오가 복제되지 않습니다", filterWarningBody = "RespectFilteringEnabled가 true입니다. 이 경험에서 Server 모드가 제대로 작동하지 않습니다.", rejoin = "텔레포터", randomServer = "무작위 서버 참가", teleporting = "텔레포트 중...", teleportFailed = "텔레포트 실패: %s", randomServerFailed = "다른 공개 서버를 찾거나 참가할 수 없습니다.", randomServerSearching = "공개 서버 검색 중...", scan = "사운드 다시 검색", languageNames = {"English", "Español", "Português", "한국어", "中文", "Русский"} }, zh = { welcome = "欢迎使用 REX SoundService", language = "语言", chooseLanguage = "选择语言以打开界面。", warningTitle = "服务器音频复制提示", warning1 = "若要通过服务器复制音频,SoundService.RespectFilteringEnabled 必须设为 FALSE。", warning2 = "如果设为 TRUE,此客户端启动的音频只会在本地播放。本脚本不会更改该设置。", warning3 = "SERVER 模式播放原始 Sound 实例。CLIENT 模式播放本地克隆。", accept = "接受并继续", browser = "声音浏览器", playback = "播放", scan = "开始 / 重新扫描(约 1 分钟)", scanning = "正在扫描游戏声音... %d%%", scanDone = "扫描完成。找到 %d 个声音。", scanEmpty = "扫描完成,但没有找到可用的声音。", scanBusy = "扫描已经在进行中。", sounds = "可用声音", selection = "选择状态", none = "未选择", one = "一个", various = "多个", selectedCount = "已选择声音:%d", clear = "清除选择", copy = "复制已选声音的 ID", mode = "播放模式", client = "客户端", server = "服务器", loop = "循环", playbackType = "播放顺序", all = "同时播放全部", oneByOne = "逐个播放", inject = "播放音频", stop = "停止", status = "状态", filteringTrue = "开启 (true)", filteringFalse = "关闭 (false)", filteringUnknown = "无法读取", filteringStatus = "RespectFilteringEnabled:%s", filteringTrueInfo = "如果为 true,此客户端启动的声音可能只在本地播放。", filteringFalseInfo = "如果为 false,体验可能允许服务器复制音频。", currentMode = "当前播放模式:%s", statusExplanation = "Server 播放使用原始 Sound 实例。Client 播放使用本地克隆。此脚本不会更改游戏设置。", idle = "就绪。", nothingSelected = "请先至少选择一个声音。", started = "已开始播放。", stopped = "播放已停止。", finished = "播放完成。", serverWarning = "RespectFilteringEnabled 当前为 TRUE。服务器复制未启用,音频可能只在客户端播放。", serverReady = "RespectFilteringEnabled 当前为 FALSE。此体验可能允许服务器复制音频。", filterUnknown = "无法读取 RespectFilteringEnabled。", copied = "声音 ID 已复制。", clipboardUnavailable = "剪贴板不可用。声音 ID:%s", shownLimit = "为保持界面流畅,仅显示前 %d 个声音。", tabInfo = "在此选择声音。再次点击已选项目即可取消选择。", serverModeInfo = "Server 使用原始 Sound 实例。是否复制取决于体验中的 RespectFilteringEnabled 设置。", clientModeInfo = "Client 创建并播放本地克隆。其他玩家听不到。", stay = "留在游戏中", leave = "离开游戏", leaveMessage = "由于 RespectFilteringEnabled 为 true,正在离开游戏。", filterWarningTitle = "服务器音频将无法复制", filterWarningBody = "RespectFilteringEnabled 为 true。在此体验中,Server 模式无法正常工作。", rejoin = "传送器", randomServer = "加入随机服务器", teleporting = "正在传送...", teleportFailed = "传送失败:%s", randomServerFailed = "无法找到或加入其他公共服务器。", randomServerSearching = "正在搜索公共服务器...", scan = "重新扫描声音", languageNames = {"English", "Español", "Português", "한국어", "中文", "Русский"} }, ru = { welcome = "Добро пожаловать в REX SoundService", language = "Язык", chooseLanguage = "Выберите язык, чтобы открыть интерфейс.", warningTitle = "УВЕДОМЛЕНИЕ О SERVER-SIDE АУДИО", warning1 = "Для репликации аудио через сервер параметр SoundService.RespectFilteringEnabled должен иметь значение FALSE.", warning2 = "Если установлено TRUE, звук, запущенный этим клиентом, будет слышен только локально. Скрипт не изменяет эту настройку.", warning3 = "Режим SERVER воспроизводит исходный объект Sound. Режим CLIENT воспроизводит локальную копию.", accept = "Принять и продолжить", browser = "Браузер звуков", playback = "Воспроизведение", scan = "Начать / повторить сканирование (около 1 минуты)", scanning = "Поиск звуков игры... %d%%", scanDone = "Сканирование завершено. Найдено звуков: %d.", scanEmpty = "Сканирование завершено, но подходящие звуки не найдены.", scanBusy = "Сканирование уже выполняется.", sounds = "Доступные звуки", selection = "Выбор", none = "Нет", one = "Один", various = "Несколько", selectedCount = "Выбрано звуков: %d", clear = "Сбросить выбор", copy = "Копировать ID выбранных звуков", mode = "Режим воспроизведения", client = "Клиент", server = "Сервер", loop = "Повтор", playbackType = "Порядок воспроизведения", all = "Все сразу", oneByOne = "По одному", inject = "Воспроизвести аудио", stop = "Остановить", status = "Статус", filteringTrue = "Включено (true)", filteringFalse = "Выключено (false)", filteringUnknown = "Недоступно", filteringStatus = "RespectFilteringEnabled: %s", filteringTrueInfo = "Если true, звуки, запущенные этим клиентом, могут остаться локальными.", filteringFalseInfo = "Если false, игра может разрешать репликацию звука через сервер.", currentMode = "Текущий режим воспроизведения: %s", statusExplanation = "Режим Server использует исходный объект Sound. Режим Client использует локальную копию. Скрипт не меняет настройки игры.", idle = "Готово.", nothingSelected = "Сначала выберите хотя бы один звук.", started = "Воспроизведение начато.", stopped = "Воспроизведение остановлено.", finished = "Воспроизведение завершено.", serverWarning = "RespectFilteringEnabled имеет значение TRUE. Репликация сервера не включена; звук может быть слышен только на клиенте.", serverReady = "RespectFilteringEnabled имеет значение FALSE. Игра может разрешать репликацию через сервер.", filterUnknown = "Не удалось прочитать RespectFilteringEnabled.", copied = "ID звука скопирован.", clipboardUnavailable = "Буфер обмена недоступен. ID звука: %s", shownLimit = "Для плавной работы интерфейса показаны первые %d звуков.", tabInfo = "Выбирайте звуки здесь. Повторное нажатие на выбранный пункт снимает выбор.", serverModeInfo = "Server использует исходный объект Sound. Репликация зависит от настройки RespectFilteringEnabled в игре.", clientModeInfo = "Client создает и воспроизводит локальную копию. Другие игроки ее не услышат.", stay = "Остаться в игре", leave = "Выйти из игры", leaveMessage = "Выход из игры, так как RespectFilteringEnabled включён.", filterWarningTitle = "Серверное аудио не будет реплицироваться", filterWarningBody = "RespectFilteringEnabled имеет значение true. Режим Server не будет работать должным образом в этой игре.", rejoin = "Телепорт", randomServer = "Перейти на случайный сервер", teleporting = "Телепортация...", teleportFailed = "Ошибка телепортации: %s", randomServerFailed = "Не удалось найти или подключиться к другому общедоступному серверу.", randomServerSearching = "Поиск общедоступного сервера...", scan = "Повторно сканировать звуки", languageNames = {"English", "Español", "Português", "한국어", "中文", "Русский"} } } local language = "en" local function T(key, ...) local pack = TEXT[language] or TEXT.en local value = pack[key] or TEXT.en[key] or key if select("#", ...) > 0 then local ok, formatted = pcall(string.format, value, ...) if ok then return formatted end end return value end local function notify(content, duration) Rayfield:Notify({ Title = "REX SoundService", Content = content, Duration = duration or 4, Image = 4483362458 }) end local Window = Rayfield:CreateWindow({ Name = "REX SoundService", LoadingTitle = "REX SoundService", LoadingSubtitle = "REX SoundService", ConfigurationSaving = { Enabled = false }, Discord = {Enabled = false, Invite = "", RememberJoins = false}, KeySystem = false, DisableRayfieldPrompts = true }) -- The language picker is the only welcome screen. Choosing a language opens the interface. local WelcomeTab = Window:CreateTab("REX", 4483362458) WelcomeTab:CreateSection("REX SoundService") local WelcomeText = WelcomeTab:CreateLabel(T("chooseLanguage")) local started = false local initializeInterface local LanguageDropdown = WelcomeTab:CreateDropdown({ Name = T("language"), Options = TEXT.en.languageNames, CurrentOption = {}, MultipleOptions = false, Flag = "REX_Language", Callback = function(options) local selected = options and options[1] local map = { ["English"] = "en", ["Español"] = "es", ["Português"] = "pt", ["한국어"] = "ko", ["中文"] = "zh", ["Русский"] = "ru" } language = map[selected] or "en" pcall(function() WelcomeText:Set(T("chooseLanguage")) end) if not started and initializeInterface then started = true initializeInterface() end end }) -- Read the live SoundService property exposed to the client. -- Return only a real boolean; never convert a failed read into true/false. local function getFilteringState() local ok, value = pcall(function() return SoundService.RespectFilteringEnabled end) if not ok or typeof(value) ~= "boolean" then return nil end return value end initializeInterface = function() local SoundTab = Window:CreateTab(T("browser"), 4483362458) local PlaybackTab = Window:CreateTab(T("playback"), 4483362458) local StatusTab = Window:CreateTab(T("status"), 4483362458) local state = { sounds = {}, soundByOption = {}, selected = {}, selectedList = {}, dropdownOptions = {}, mode = "CLIENT", playbackKind = "ALL", loopEnabled = false, isPlaying = false, playbackToken = 0, activeClones = {}, activeOriginals = {}, originalLoopValues = {}, scanning = false, scanToken = 0 } local StatusLabel local SelectionLabel local CountLabel local SoundDropdown local StatusCurrentLabel local StatusModeLabel local function updateSelectionDisplay() local selectedList = {} for sound in pairs(state.selected) do if sound and sound.Parent and sound:IsA("Sound") then table.insert(selectedList, sound) end end table.sort(selectedList, function(a, b) return a:GetFullName():lower() < b:GetFullName():lower() end) state.selectedList = selectedList local count = #selectedList local typeText = count == 0 and T("none") or (count == 1 and T("one") or T("various")) if SelectionLabel then pcall(function() SelectionLabel:Set(T("selection") .. ": " .. typeText) end) end if CountLabel then pcall(function() CountLabel:Set(T("selectedCount", count)) end) end end local function setStatus(message) if StatusLabel then pcall(function() StatusLabel:Set(message) end) end end local function updateModeStatus() local filtering = getFilteringState() local filteringText = filtering == true and T("filteringTrue") or filtering == false and T("filteringFalse") or T("filteringUnknown") if StatusCurrentLabel then pcall(function() StatusCurrentLabel:Set(T("filteringStatus", filteringText)) end) end if StatusModeLabel then local modeText = state.mode == "SERVER" and T("server") or T("client") pcall(function() StatusModeLabel:Set(T("currentMode", modeText)) end) end end local function clearSelection() table.clear(state.selected) table.clear(state.selectedList) if SoundDropdown then pcall(function() SoundDropdown:Set({}) end) end updateSelectionDisplay() end SoundTab:CreateSection(T("sounds")) SoundTab:CreateLabel(T("tabInfo")) SelectionLabel = SoundTab:CreateLabel(T("selection") .. ": " .. T("none")) CountLabel = SoundTab:CreateLabel(T("selectedCount", 0)) SoundDropdown = SoundTab:CreateDropdown({ Name = T("sounds"), Options = {}, CurrentOption = {}, MultipleOptions = true, Flag = "REX_SoundSelection", Callback = function(options) local chosen = {} if type(options) == "table" then for _, option in ipairs(options) do local sound = state.soundByOption[option] if sound and sound.Parent then chosen[sound] = true end end end state.selected = chosen updateSelectionDisplay() end }) SoundTab:CreateButton({ Name = T("clear"), Callback = clearSelection }) SoundTab:CreateButton({ Name = T("scan"), Callback = function() -- The scan function is assigned below before the user can press this. if state.scanFunction then state.scanFunction() end end }) SoundTab:CreateButton({ Name = T("copy"), Callback = function() updateSelectionDisplay() local sound = state.selectedList[1] if not sound then notify(T("nothingSelected"), 3) return end local lines = {} for _, selectedSound in ipairs(state.selectedList) do table.insert(lines, string.format("%s -- ID: %s", selectedSound.Name, selectedSound.SoundId or "")) end local payload = table.concat(lines, "\n") if type(setclipboard) == "function" then local ok = pcall(setclipboard, payload) if ok then notify(T("copied") .. " (" .. tostring(#lines) .. ")", 3) return end end notify(T("clipboardUnavailable", payload), 8) end }) local function cleanupPlayback() for _, clone in ipairs(state.activeClones) do pcall(function() clone:Stop() clone:Destroy() end) end table.clear(state.activeClones) for _, original in ipairs(state.activeOriginals) do pcall(function() original:Stop() end) end table.clear(state.activeOriginals) for original, oldLooped in pairs(state.originalLoopValues) do if original and original.Parent then pcall(function() original.Looped = oldLooped end) end end table.clear(state.originalLoopValues) state.isPlaying = false end local function stopPlayback(showStatus) state.playbackToken += 1 cleanupPlayback() if showStatus ~= false then setStatus(T("stopped")) end end local function preparePlaybackSound(original) if not original or not original.Parent or not original:IsA("Sound") then return nil, nil end if state.mode == "CLIENT" then local ok, clone = pcall(function() return original:Clone() end) if not ok or not clone then return nil, nil end clone.Name = "REX_Local_" .. original.Name clone.Looped = false clone.PlayOnRemove = false local parent = original.Parent if not parent or not parent:IsDescendantOf(game) then parent = SoundService end clone.Parent = parent table.insert(state.activeClones, clone) return clone, clone end if state.originalLoopValues[original] == nil then state.originalLoopValues[original] = original.Looped end original.Looped = false if not table.find(state.activeOriginals, original) then table.insert(state.activeOriginals, original) end return original, nil end local function playOne(original, token) local playbackSound, clone = preparePlaybackSound(original) if not playbackSound then return end local ended = false local connection = playbackSound.Ended:Connect(function() ended = true end) -- Reset the position before every pass. This is important when the -- same original Sound is replayed by the loop after reaching its end. local ok = pcall(function() playbackSound:Stop() playbackSound.TimePosition = 0 playbackSound:Play() end) if not ok then connection:Disconnect() if clone then pcall(function() clone:Destroy() end) for index = #state.activeClones, 1, -1 do if state.activeClones[index] == clone then table.remove(state.activeClones, index) break end end end return end local startTime = os.clock() local hasStarted = false while token == state.playbackToken and playbackSound.Parent and not ended do if playbackSound.IsPlaying then hasStarted = true end -- Ended is the primary completion signal. TimeLength is a -- fallback for assets/contexts where Ended is not delivered. if hasStarted and playbackSound.TimeLength > 0 and playbackSound.TimePosition >= playbackSound.TimeLength - 0.05 then break end -- Do not wait forever for an unavailable or unplayable asset. if not hasStarted and os.clock() - startTime >= 20 then break end task.wait(0.05) end connection:Disconnect() if clone then pcall(function() clone:Stop() clone:Destroy() end) for index = #state.activeClones, 1, -1 do if state.activeClones[index] == clone then table.remove(state.activeClones, index) break end end end end local function finishPlayback(token) if token ~= state.playbackToken then return end cleanupPlayback() setStatus(T("finished")) end local function startPlayback() updateSelectionDisplay() local list = {} for _, sound in ipairs(state.selectedList) do if sound and sound.Parent and sound:IsA("Sound") then table.insert(list, sound) end end if #list == 0 then setStatus(T("nothingSelected")) notify(T("nothingSelected"), 3) return end stopPlayback(false) state.playbackToken += 1 local token = state.playbackToken state.isPlaying = true setStatus(T("started")) task.spawn(function() while token == state.playbackToken do if state.playbackKind == "ALL" then -- Start the selected sounds together, then wait until -- every sound in this pass has finished before replaying. local remaining = #list for _, sound in ipairs(list) do task.spawn(function() playOne(sound, token) remaining -= 1 end) end while token == state.playbackToken and remaining > 0 do task.wait(0.05) end else -- One-by-one mode completes the full list before the -- next loop pass begins. for _, sound in ipairs(list) do if token ~= state.playbackToken then break end setStatus(T("started") .. " " .. sound.Name) playOne(sound, token) end end -- Loop means replay the complete selection continuously. -- Turning it off lets the current pass finish, then exits. if token ~= state.playbackToken or not state.loopEnabled then break end task.wait(0.1) end finishPlayback(token) end) end PlaybackTab:CreateSection(T("mode")) PlaybackTab:CreateDropdown({ Name = T("mode"), Options = {T("client"), T("server")}, CurrentOption = {T("client")}, MultipleOptions = false, Flag = "REX_PlaybackMode", Callback = function(options) local value = options and options[1] state.mode = (value == T("server")) and "SERVER" or "CLIENT" updateModeStatus() end }) PlaybackTab:CreateDropdown({ Name = T("playbackType"), Options = {T("all"), T("oneByOne")}, CurrentOption = {T("all")}, MultipleOptions = false, Flag = "REX_PlaybackKind", Callback = function(options) local value = options and options[1] state.playbackKind = (value == T("oneByOne")) and "ONE_BY_ONE" or "ALL" end }) PlaybackTab:CreateToggle({ Name = T("loop"), CurrentValue = false, Flag = "REX_Loop", Callback = function(value) state.loopEnabled = value end }) PlaybackTab:CreateButton({ Name = T("inject"), Callback = startPlayback }) PlaybackTab:CreateButton({ Name = T("stop"), Callback = function() stopPlayback(true) end }) StatusTab:CreateSection(T("status")) StatusLabel = StatusTab:CreateLabel(T("idle")) StatusCurrentLabel = StatusTab:CreateLabel(T("filteringStatus", T("filteringUnknown"))) StatusModeLabel = StatusTab:CreateLabel(T("currentMode", T("client"))) StatusTab:CreateLabel(T("statusExplanation")) StatusTab:CreateLabel(T("filteringTrueInfo")) StatusTab:CreateLabel(T("filteringFalseInfo")) StatusTab:CreateLabel(T("serverModeInfo")) StatusTab:CreateLabel(T("clientModeInfo")) -- Show the replication warning controls only when the live property -- is explicitly TRUE. FALSE or an unreadable value keeps this section hidden. if getFilteringState() == true then StatusTab:CreateSection(T("filterWarningTitle")) StatusTab:CreateLabel(T("filterWarningBody")) StatusTab:CreateButton({ Name = T("stay"), Callback = function() notify(T("idle"), 3) end }) StatusTab:CreateButton({ Name = T("leave"), Callback = function() LocalPlayer:Kick(T("leaveMessage")) end }) end StatusTab:CreateSection(T("rejoin")) StatusTab:CreateButton({ Name = T("rejoin"), Callback = function() setStatus(T("teleporting")) local ok, err = pcall(function() TeleportService:TeleportToPlaceInstance(game.PlaceId, game.JobId, LocalPlayer) end) if not ok then local message = T("teleportFailed", tostring(err)) setStatus(message) notify(message, 6) end end }) StatusTab:CreateButton({ Name = T("randomServer"), Callback = function() setStatus(T("randomServerSearching")) task.spawn(function() local ok, result = pcall(function() local endpoint = "https://games.roblox.com/v1/games/" .. tostring(game.PlaceId) .. "/servers/Public?sortOrder=Asc&limit=100" local response = game:HttpGet(endpoint) local decoded = HttpService:JSONDecode(response) local candidates = {} for _, server in ipairs(decoded.data or {}) do if server.id and server.id ~= game.JobId and (server.playing or 0) < (server.maxPlayers or math.huge) then table.insert(candidates, server.id) end end if #candidates == 0 then error(T("randomServerFailed")) end local targetId = candidates[math.random(1, #candidates)] TeleportService:TeleportToPlaceInstance(game.PlaceId, targetId, LocalPlayer) end) if not ok then local message = T("randomServerFailed") .. " " .. tostring(result) setStatus(message) notify(message, 7) end end) end }) -- Read-only status. The value is read from the live SoundService -- property available to the client; this script never changes it. local warnedFilteringTrue = false local function refreshFilteringStatus() updateModeStatus() local filteringNow = getFilteringState() if filteringNow == true and not warnedFilteringTrue then warnedFilteringTrue = true notify(T("filterWarningBody") .. " " .. T("stay") .. " / " .. T("leave"), 8) elseif filteringNow == false then warnedFilteringTrue = false end return filteringNow end refreshFilteringStatus() -- Update immediately when Roblox reports a property change. -- The periodic refresh remains as a fallback for UI/status recovery. local filteringChangedConnection pcall(function() filteringChangedConnection = SoundService:GetPropertyChangedSignal( "RespectFilteringEnabled" ):Connect(refreshFilteringStatus) end) task.spawn(function() while started do refreshFilteringStatus() task.wait(2) end if filteringChangedConnection then filteringChangedConnection:Disconnect() end end) local SCAN_DURATION = 60 local function scanSounds() if state.scanning then notify(T("scanBusy"), 3) return end state.scanning = true state.scanToken += 1 local thisScan = state.scanToken setStatus(T("scanning", 0)) task.spawn(function() local descendants = game:GetDescendants() local found = {} local addedConnection local seenIds = {} local defaultCharacterSoundNames = { running = true, jumping = true, freefalling = true, gettingup = true, landing = true, climbing = true, swimming = true, splash = true, died = true, footsteps = true } local function canonicalSoundId(soundId) local raw = tostring(soundId or ""):gsub("%s+", "") local numeric = raw:match("rbxassetid://(%d+)") or raw:match("[?&]id=(%d+)") return numeric or raw:lower() end local function isRobloxDefaultSound(object) local id = tostring(object.SoundId or ""):lower() if id:match("^rbxasset://") then return true end local ancestor = object.Parent while ancestor and ancestor ~= game do local name = tostring(ancestor.Name):lower() if name == "rbxcharactersounds" or name == "playermodule" or name == "robloxgui" then return true end ancestor = ancestor.Parent end local model = object:FindFirstAncestorOfClass("Model") if model and Players:GetPlayerFromCharacter(model) then if defaultCharacterSoundNames[tostring(object.Name):lower()] then return true end end return false end local function addSound(object) if not object or not object:IsA("Sound") or object.SoundId == "" or object.Name:match("^REX_Local_") or isRobloxDefaultSound(object) then return end local idKey = canonicalSoundId(object.SoundId) if idKey == "" or seenIds[idKey] then return end seenIds[idKey] = true table.insert(found, object) end -- Track newly-created sounds without launching another full scan. addedConnection = game.DescendantAdded:Connect(function(object) if thisScan == state.scanToken then addSound(object) end end) local total = #descendants local batches = 600 local batchSize = math.max(1, math.ceil(total / batches)) local startedAt = os.clock() local lastProgressAt = 0 for first = 1, total, batchSize do if thisScan ~= state.scanToken then if addedConnection then addedConnection:Disconnect() end state.scanning = false return end local last = math.min(first + batchSize - 1, total) for index = first, last do addSound(descendants[index]) end local elapsed = os.clock() - startedAt local progress = math.min(99, math.floor((last / math.max(total, 1)) * 100)) if elapsed - lastProgressAt >= 5 then setStatus(T("scanning", progress)) lastProgressAt = elapsed end -- 600 small batches spread over about one minute. local targetElapsed = ((last / math.max(total, 1)) * SCAN_DURATION) local waitTime = targetElapsed - (os.clock() - startedAt) if waitTime > 0 then task.wait(math.min(waitTime, 0.12)) else task.wait() end end local remaining = SCAN_DURATION - (os.clock() - startedAt) while remaining > 0 and thisScan == state.scanToken do task.wait(math.min(remaining, 0.25)) remaining = SCAN_DURATION - (os.clock() - startedAt) end if addedConnection then addedConnection:Disconnect() end if thisScan ~= state.scanToken then state.scanning = false return end table.sort(found, function(a, b) local aName = a:GetFullName():lower() local bName = b:GetFullName():lower() return aName < bName end) state.sounds = found state.soundByOption = {} local options = {} local nameCounts = {} for index = 1, #found do local sound = found[index] local baseName = tostring(sound.Name) nameCounts[baseName] = (nameCounts[baseName] or 0) + 1 local option = baseName if nameCounts[baseName] > 1 then option = string.format("%s (%d)", baseName, nameCounts[baseName]) end state.soundByOption[option] = sound table.insert(options, option) end state.dropdownOptions = options -- Remove selections whose instances disappeared. for sound in pairs(state.selected) do if not sound or not sound.Parent then state.selected[sound] = nil end end updateSelectionDisplay() pcall(function() SoundDropdown:Refresh(options) SoundDropdown:Set({}) end) state.scanning = false if #found == 0 then setStatus(T("scanEmpty")) notify(T("scanEmpty"), 5) else local completionMessage = T("scanDone", #found) setStatus(completionMessage) notify(completionMessage, 7) end end) end state.scanFunction = scanSounds scanSounds() end print("[REX SoundService V7 Definitiva] Rayfield interface loaded. Choose a language to open the interface.")