presentkim / play-sound-utils
Play any vanilla or custom sound to players in one line for axolotl-pm/PocketMine-MP
Requires
- php: ^8.4
- pocketmine/pocketmine-mp: ^5.0
Requires (Dev)
- axolotl-pm/pocketmine-mp: ^5.51
- phpstan/phpstan: ^2.3
- phpstan/phpstan-phpunit: ^2.1
- phpstan/phpstan-strict-rules: ^2.1
- phpunit/phpunit: ^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
play-sound-utils
Play any vanilla or custom sound to players in one line.
Packagist ยท Changelog ยท Report a bug ยท Request a feature
PlaySound::sendTo($player, VanillaPlaySounds::LEVELUP); // to one player, at their position $world->addSound($position, VanillaPlaySounds::MOB_CREEPER_SAY()); // to everyone near a position
๐ Why play-sound-utils?
Sending a sound by its string name means building a PlaySoundPacket by hand: coordinates, volume, pitch, and
(since Bedrock 1.26.60) three more fields. This library wraps all of it, so the same one-liner keeps working when
the packet changes:
- One line per job : to one player, to many players, or through
World::addSound() - Real
Soundobjects :PlaySoundimplementspocketmine\world\sound\Sound, so the world decides who hears it - All vanilla sounds included : every sound of Bedrock 1.26.60.5 as a typed method (
VanillaPlaySounds::LEVELUP()) or a constant for the raw name (VanillaPlaySounds::LEVELUP), grouped by category - Up to date with the protocol : supports the 1.26.60
PlaySoundPacketwith loop count, listener range bypass and playback position - Safe to call : disconnected players are skipped instead of throwing
- Small phars : an optional build tool strips every sound your plugin does not use
- Tested : run against the real server code on PHP 8.4 / 8.5, and analysed with PHPStan level 9
๐ฏ Use cases
| You are building... | Use |
|---|---|
| Feedback sounds (success, error, toggle) | FeedbackSounds::success()->send($player) |
| Let players turn feedback sounds off or down | FeedbackPreferences::registerCommand($this) |
| Show a tip only the first time | FirstUseHints::once($player, "myplugin.tip") |
| Minigame events for everyone in an arena | PlaySound::broadcastTo() |
| Sounds at a block or entity position | World::addSound() with a PlaySound |
| Looping ambience or music | loopCount and playbackPositionSeconds |
| Sounds from a resource pack (custom sounds) | new PlaySound("your.custom.sound") |
๐ฆ Installation
composer require presentkim/play-sound-utils
| Requirement | Version |
|---|---|
| Server | axolotl-pm/PocketMine-MP (fork of PocketMine-MP 5) |
| PHP | 8.4 or newer |
The Poggit virion for the original PocketMine-MP 5.44 and older is kept on the
legacy/pmmp-5.44branch (no longer maintained).
๐ Quick start
All classes are in kim\present\utils\playsound.
use kim\present\utils\playsound\PlaySound; use kim\present\utils\playsound\VanillaPlaySounds; // 1. To one player (at the player's position) PlaySound::sendTo($player, "random.levelup"); // 2. To several players PlaySound::broadcastTo($players, "random.levelup", volume: 0.8, pitch: 1.2); // 3. Through the world: the world sends it to the players who can hear it $world->addSound($position, new PlaySound("random.levelup")); // 4. A vanilla sound without typing its name $world->addSound($position, VanillaPlaySounds::LEVELUP());
Sound options
PlaySound is a mutable value object. Every option is a constructor argument and has a fluent setter:
$sound = new PlaySound("music.game", volume: 0.5, pitch: 1.0, loopCount: 3, playbackPositionSeconds: 12.5); $sound->setVolume(1.0)->setPitch(0.9)->setBypassListenerRangeCheck(true); $sound->send($player); // at the player's position $sound->send($players, $vec); // at a position, to a list of players
VanillaPlaySounds::XXX()returns a new copy each time, so changing it never affects other callers.
๐ Examples
Sounds with World::addSound()
use kim\present\utils\playsound\PlaySound; use pocketmine\math\Vector3; use pocketmine\world\World; function sendCustomSound(World $world, Vector3 $vec) : void{ $world->addSound($vec, new PlaySound("random.levelup", volume: 0.8, pitch: 1.2)); }
Consistent feedback with FeedbackSounds
use kim\present\utils\playsound\FeedbackSounds; FeedbackSounds::success()->send($player); FeedbackSounds::error()->send($player); FeedbackSounds::toggleOn()->setVolume(0.4)->send($player); // every method returns a new PlaySound
| Method | Use for | Sound |
|---|---|---|
success() |
an action succeeded | random.orb |
error() |
denied or failed | block.false_permissions |
toggleOn() / toggleOff() |
a setting changed (high / low) | random.click |
open() / close() |
a menu or container | ui.drawer_open / ui.drawer_close |
confirm() |
placed or saved | vault.place |
warn() |
needs attention, not an error | note.bell (low pitch) |
dispose() |
an item destroyed or discarded | random.fizz |
Player settings with FeedbackPreferences and FirstUseHints
FeedbackSounds sends nothing to a player who turned feedback sounds off, and multiplies the volume by the player's
volume setting. Register the command once in onEnable() so players can change it:
use kim\present\utils\playsound\FeedbackPreferences; use kim\present\utils\playsound\FirstUseHints; protected function onEnable() : void{ FeedbackPreferences::registerCommand($this); // /feedbacksound [on|off|volume <0~1>] } FeedbackPreferences::setEnabled($player, false); FeedbackPreferences::setVolume($player, 0.5); if(FirstUseHints::once($player, "myplugin.shop-tip")){ // true only the first time for this player $player->sendTip("..."); }
/feedbacksoundshows the current state,on/offtoggle it (with the toggle sounds), andvolume 0.5sets the volume. Messages are in Korean when the player's language is Korean, otherwise English.- If the server already has a
feedbacksoundcommand,registerCommand()does nothing. Every plugin that usesFeedbackSoundscan call it, and only the first one registers it. - The permission
playsoundutils.command.feedbacksoundis registered in code and istruefor everyone by default. - Only
FeedbackSoundsand sounds withsetRespectFeedbackPreferences()are filtered, and only when sent withsend(). Sounds played throughWorld::addSound()are not.
Build the packet yourself
use kim\present\utils\playsound\PlaySound; // Optional trailing parameters: serverSoundHandle, loopCount, bypassListenerRangeCheck, playbackPositionSeconds $packet = PlaySound::createPacket($vec, "random.levelup", volume: 1.0, pitch: 1.0); $player->getNetworkSession()->sendDataPacket($packet);
Looping a sound and starting in the middle
// Repeats 3 times and starts 30 seconds into the track $music = (new PlaySound("music.game")) ->setLoopCount(3) ->setPlaybackPositionSeconds(30.0); $music->send($player);
Constants or methods?
use kim\present\utils\playsound\VanillaPlaySounds; $name = VanillaPlaySounds::LEVELUP; // string "random.levelup": for sendTo() / broadcastTo() / createPacket() $sound = VanillaPlaySounds::LEVELUP(); // PlaySound object: for World::addSound() / send()
Category traits are generated under kim\present\utils\playsound\defaults
(category ui becomes VanillaPlaySoundsUiTrait) and are composed into the final VanillaPlaySounds class.
๐ API reference
PlaySound
| Member | Description |
|---|---|
new PlaySound(string $soundName, float $volume = 1.0, float $pitch = 1.0, ?int $serverSoundHandle = null, int $loopCount = 0, bool $bypassListenerRangeCheck = false, ?float $playbackPositionSeconds = null) |
Create a sound. Implements pocketmine\world\sound\Sound |
getSoundName() / setSoundName(string) |
Sound name, e.g. random.levelup |
getVolume() / setVolume(float) |
Volume, based on 1.0 |
getPitch() / setPitch(float) |
Pitch, based on 1.0 |
getServerSoundHandle() / setServerSoundHandle(?int) |
Optional sound handle (added in 1.26.20) |
getLoopCount() / setLoopCount(int) |
How many times the client repeats the sound, 0 plays it once (new in 2.0.0) |
isBypassListenerRangeCheck() / setBypassListenerRangeCheck(bool) |
Play even if the client is out of listener range (new in 2.0.0) |
getPlaybackPositionSeconds() / setPlaybackPositionSeconds(?float) |
Position in seconds to start playback from, null for the start (new in 2.0.0) |
encode(Vector3 $pos) : PlaySoundPacket[] |
The packet list used by World::addSound() |
send(Player|Player[] $recipients, ?Vector3 $vec = null) : void |
Send to one or more players. $vec null plays at each player's own position. Disconnected players are skipped |
static sendTo(Player $player, string $soundName, float $volume = 1.0, float $pitch = 1.0) : void |
Send by name at the player's position. Does nothing if disconnected |
static broadcastTo(Player[] $recipients, string $soundName, float $volume = 1.0, float $pitch = 1.0) : void |
sendTo() for each player |
static createPacket(Vector3 $vec, string $soundName, float $volume = 1.0, float $pitch = 1.0, ?int $serverSoundHandle = null, int $loopCount = 0, bool $bypassListenerRangeCheck = false, ?float $playbackPositionSeconds = null) : PlaySoundPacket |
Build the packet only |
All setters return $this.
FeedbackSounds
Static presets that each return a new PlaySound at a modest volume: success(), error(), toggleOn(),
toggleOff(), open(), close(), confirm(), warn() and dispose().
PlaySound also has setRespectFeedbackPreferences(bool $respect = true) and isRespectFeedbackPreferences()
(new in 4.2.0). With it on, send() skips players whose feedback sounds are off and scales the volume. The
FeedbackSounds presets turn it on, so call setRespectFeedbackPreferences(false) to always play.
FeedbackPreferences
| Member | Description |
|---|---|
static isEnabled(Player) : bool |
Whether the player wants feedback sounds (default true) |
static setEnabled(Player, bool) : void |
Turn feedback sounds on or off for the player |
static getVolume(Player) : float |
Volume multiplier from 0.0 to 1.0 (default 1.0) |
static setVolume(Player, float) : void |
Set the volume. Throws InvalidArgumentException outside 0.0 to 1.0 |
static registerCommand(PluginBase) : void |
Register /feedbacksound, or do nothing if that command already exists |
The setters throw RuntimeException if the settings file cannot be written.
FirstUseHints
FirstUseHints::once(Player $player, string $key) : bool records that the player has seen the hint and returns
true the first time, false afterwards. Use <plugin>.<id> as the key.
VanillaPlaySounds
Every vanilla sound name is available twice: VanillaPlaySounds::NAME (string constant) and
VanillaPlaySounds::NAME() (new PlaySound). Names are the sound name in upper case with dots replaced by _
(mob.zombie.say becomes MOB_ZOMBIE_SAY); where it does not collide, a shorter alias without the first segment is
also generated (ZOMBIE_SAY). The list is for Bedrock 1.26.60.5.
๐๏ธ Where the settings are stored
Every plugin bundles this library under its own namespace (shading), so one server can run several copies of
FeedbackPreferences. A static variable would be separate in each copy, so the setting must live in a place all of
them read directly. Two places were considered:
- Player data (
PlayerDataSaveEventto write,Server::getOfflinePlayerData()to read). Rejected, because in PocketMine 5.51 the data is written when the player quits (Player::save()), andgetOfflinePlayerData()reads it from disk and not from the online player. A toggle would not reach the other copies while the player is online, and the save event of every copy would need the new value from somewhere, which is the shared storage we were looking for. - A shared file in the server data folder (chosen).
presentkim_feedback.jsonnext to the server's other data. Each copy keeps a small cache and compares the file's signature (inode, modification time, size) with astat()call on every read, so a change made by one copy is seen by the others on their next call. Writes go to a temporary file that replaces the real one withrename(), so a reader never sees half a file and the inode always changes. It survives a server restart, and the server runs plugins on one thread, so copies never write at the same time.
Records are keyed by the lowercase player name. A missing or broken file counts as "no settings".
โ๏ธ Trimming unused sounds from your phar
VanillaPlaySounds holds thousands of constants and methods. If your plugin uses a handful of them, the bundled copy
is dead weight. The prune tool rewrites your built plugin phar so it only keeps the members that are actually used:
- removes the generated
VanillaPlaySounds*Traitfiles - inlines only the used constants and methods into the
VanillaPlaySoundsclass
It reads the PHP files inside the phar, so it must run after the plugin phar is built with its vendor libraries
(namespace-shaded or not). The class is found by its short name, so a shaded name such as
MyPlugin\libs\kim\present\utils\playsound\VanillaPlaySounds works, and so do use ... as Alias; imports and
constant uses (VanillaPlaySounds::LEVELUP).
Usage
The tool is installed as a Composer bin. phar.readonly must be disabled:
# one phar php -d phar.readonly=0 vendor/bin/prune-vanilla-play-sounds-phar.php .releases/MyPlugin.phar # every .phar in a directory, or a glob php -d phar.readonly=0 vendor/bin/prune-vanilla-play-sounds-phar.php .releases php -d phar.readonly=0 vendor/bin/prune-vanilla-play-sounds-phar.php ".releases/*.phar"
- The phar is replaced in place. If it is locked (e.g. on Windows), the result is written next to it as
MyPlugin.trimmed.phar. - A phar that does not contain
VanillaPlaySoundsis left untouched. - Only sounds referenced statically are kept. If you build sound names dynamically
(
constant("VanillaPlaySounds::$name")), do not prune, or pass plain strings toPlaySoundinstead.
In a release build
Run it as the last step, after the plugin phar has been built and the vendor libraries have been shaded into it. Example for GitHub Actions:
- name: Install dependencies run: composer install --no-dev --optimize-autoloader - name: Build the plugin phar (shading vendor libraries) run: php -d phar.readonly=0 build/build-phar.php # your own build script - name: Prune unused VanillaPlaySounds entries run: php -d phar.readonly=0 vendor/bin/prune-vanilla-play-sounds-phar.php .releases
If the build does not keep vendor/ around, download the tool instead (both files are required, side by side):
base=https://raw.githubusercontent.com/presentkim-pm/play-sound-utils/main/tools wget -P tools "$base/prune-vanilla-play-sounds-phar.php" "$base/PruneVanillaPlaySounds.php" php -d phar.readonly=0 tools/prune-vanilla-play-sounds-phar.php .releases
๐ Regenerating the sound list
VanillaPlaySounds and its category traits are generated from Mojang's
sound_definitions.json.
To update them for a new Bedrock version:
php build/VanillaPlaySounds.generator.php
The script downloads the latest version.json and sound_definitions.json from Mojang/bedrock-samples
(so it needs network access), then rewrites src/kim/present/utils/playsound/VanillaPlaySounds.php and every trait in
src/kim/present/utils/playsound/defaults/ from the two templates in build/. Do not edit the generated files by hand.
๐งช Development
composer install --ignore-platform-req='ext-*' composer analyse # PHPStan level 9 with strict rules composer test
The tests run against the real axolotl-pm/pocketmine-mp code without its native extensions.
๐ License
Distributed under the MIT License. See LICENSE for more information.