SoundManager .java

net.minecraft.client.audio.SoundManager (class, 544 lines): members: SoundSystemStarterThread, playingSoundPoolEntries, setSoundCategoryVolume, loaded.

net.minecraft.client.audioclass544 linesclient20.4 KB

API Surface (20)

void reloadSoundSystem()
void run()
void message(String p_message_1_, int p_message_2_)
void importantMessage(String p_importantMessage_1_, int p_importantMessage_2_)
void errorMessage(String p_errorMessage_1_, String p_errorMessage_2_, int p_errorMessage_3_)
void setSoundCategoryVolume(SoundCategory category, float volume)
void unloadSoundSystem()
void stopAllSounds()
void updateAllSounds()
boolean isSoundPlaying(ISound sound)
void stopSound(ISound sound)
void playSound(ISound p_sound)
void pauseAllSounds()
void resumeAllSounds()
void playDelayedSound(ISound sound, int delay)
URLConnection openConnection(final URL p_openConnection_1_)
void connect()
InputStream getInputStream()
void setListener(EntityPlayer player, float p_148615_2_)
boolean playing(String p_playing_1_)

Fields & Constants (14)

LOG_MARKER
logger
sndHandler
options
sndSystem
loaded
playTime
playingSounds
invPlayingSounds
playingSoundPoolEntries
categorySounds
tickableSounds
delayedSounds
playingSoundsStopTime

String literals (7)

"SOUNDS"
"Error linking with the LibraryJavaSound plug-in"
"Error in class \'"
"Sound engine started"
"Sound Library Loader"
"mcsounddomain"
"TODO: Sanely handle url exception! :D"

Full Source

SoundManager.java544 lines · MCP 1.8.9 · verbatimOriginal ↗
1
package net.minecraft.client.audio;
2
3
import com.google.common.collect.BiMap;
4
import com.google.common.collect.HashBiMap;
5
import com.google.common.collect.HashMultimap;
6
import com.google.common.collect.Lists;
7
import com.google.common.collect.Maps;
8
import com.google.common.collect.Multimap;
9
import io.netty.util.internal.ThreadLocalRandom;
10
import java.io.IOException;
11
import java.io.InputStream;
12
import java.net.MalformedURLException;
13
import java.net.URL;
14
import java.net.URLConnection;
15
import java.net.URLStreamHandler;
16
import java.util.Iterator;
17
import java.util.List;
18
import java.util.Map;
19
import java.util.Map.Entry;
20
import net.minecraft.client.Minecraft;
21
import net.minecraft.client.settings.GameSettings;
22
import net.minecraft.entity.player.EntityPlayer;
23
import net.minecraft.util.MathHelper;
24
import net.minecraft.util.ResourceLocation;
25
import org.apache.logging.log4j.LogManager;
26
import org.apache.logging.log4j.Logger;
27
import org.apache.logging.log4j.Marker;
28
import org.apache.logging.log4j.MarkerManager;
29
import paulscode.sound.SoundSystem;
30
import paulscode.sound.SoundSystemConfig;
31
import paulscode.sound.SoundSystemException;
32
import paulscode.sound.SoundSystemLogger;
33
import paulscode.sound.Source;
34
import paulscode.sound.codecs.CodecJOrbis;
35
import paulscode.sound.libraries.LibraryLWJGLOpenAL;
36
37
public class SoundManager
38
{
39
    /** The marker used for logging */
40
    private static final Marker LOG_MARKER = MarkerManager.getMarker("SOUNDS");
41
    private static final Logger logger = LogManager.getLogger();
42
43
    /** A reference to the sound handler. */
44
    private final SoundHandler sndHandler;
45
46
    /** Reference to the GameSettings object. */
47
    private final GameSettings options;
48
49
    /** A reference to the sound system. */
50
    private SoundManager.SoundSystemStarterThread sndSystem;
51
52
    /** Set to true when the SoundManager has been initialised. */
53
    private boolean loaded;
54
55
    /** A counter for how long the sound manager has been running */
56
    private int playTime = 0;
57
    private final Map<String, ISound> playingSounds = HashBiMap.<String, ISound>create();
58
    private final Map<ISound, String> invPlayingSounds;
59
    private Map<ISound, SoundPoolEntry> playingSoundPoolEntries;
60
    private final Multimap<SoundCategory, String> categorySounds;
61
    private final List<ITickableSound> tickableSounds;
62
    private final Map<ISound, Integer> delayedSounds;
63
    private final Map<String, Integer> playingSoundsStopTime;
64
65
    public SoundManager(SoundHandler p_i45119_1_, GameSettings p_i45119_2_)
66
    {
67
        this.invPlayingSounds = ((BiMap)this.playingSounds).inverse();
68
        this.playingSoundPoolEntries = Maps.<ISound, SoundPoolEntry>newHashMap();
69
        this.categorySounds = HashMultimap.<SoundCategory, String>create();
70
        this.tickableSounds = Lists.<ITickableSound>newArrayList();
71
        this.delayedSounds = Maps.<ISound, Integer>newHashMap();
72
        this.playingSoundsStopTime = Maps.<String, Integer>newHashMap();
73
        this.sndHandler = p_i45119_1_;
74
        this.options = p_i45119_2_;
75
76
        try
77
        {
78
            SoundSystemConfig.addLibrary(LibraryLWJGLOpenAL.class);
79
            SoundSystemConfig.setCodec("ogg", CodecJOrbis.class);
80
        }
81
        catch (SoundSystemException soundsystemexception)
82
        {
83
            logger.error(LOG_MARKER, (String)"Error linking with the LibraryJavaSound plug-in", (Throwable)soundsystemexception);
84
        }
85
    }
86
87
    public void reloadSoundSystem()
88
    {
89
        this.unloadSoundSystem();
90
        this.loadSoundSystem();
91
    }
92
93
    /**
94
     * Tries to add the paulscode library and the relevant codecs. If it fails, the master volume  will be set to zero.
95
     */
96
    private synchronized void loadSoundSystem()
97
    {
98
        if (!this.loaded)
99
        {
100
            try
101
            {
102
                (new Thread(new Runnable()
103
                {
104
                    public void run()
105
                    {
106
                        SoundSystemConfig.setLogger(new SoundSystemLogger()
107
                        {
108
                            public void message(String p_message_1_, int p_message_2_)
109
                            {
110
                                if (!p_message_1_.isEmpty())
111
                                {
112
                                    SoundManager.logger.info(p_message_1_);
113
                                }
114
                            }
115
                            public void importantMessage(String p_importantMessage_1_, int p_importantMessage_2_)
116
                            {
117
                                if (!p_importantMessage_1_.isEmpty())
118
                                {
119
                                    SoundManager.logger.warn(p_importantMessage_1_);
120
                                }
121
                            }
122
                            public void errorMessage(String p_errorMessage_1_, String p_errorMessage_2_, int p_errorMessage_3_)
123
                            {
124
                                if (!p_errorMessage_2_.isEmpty())
125
                                {
126
                                    SoundManager.logger.error("Error in class \'" + p_errorMessage_1_ + "\'");
127
                                    SoundManager.logger.error(p_errorMessage_2_);
128
                                }
129
                            }
130
                        });
131
                        SoundManager.this.sndSystem = SoundManager.this.new SoundSystemStarterThread();
132
                        SoundManager.this.loaded = true;
133
                        SoundManager.this.sndSystem.setMasterVolume(SoundManager.this.options.getSoundLevel(SoundCategory.MASTER));
134
                        SoundManager.logger.info(SoundManager.LOG_MARKER, "Sound engine started");
135
                    }
136
                }, "Sound Library Loader")).start();
137
            }
138
            catch (RuntimeException runtimeexception)
139
            {
140
                logger.error(LOG_MARKER, (String)"Error starting SoundSystem. Turning off sounds & music", (Throwable)runtimeexception);
141
                this.options.setSoundLevel(SoundCategory.MASTER, 0.0F);
142
                this.options.saveOptions();
143
            }
144
        }
145
    }
146
147
    /**
148
     * Returns the sound level (between 0.0 and 1.0) for a category, but 1.0 for the master sound category
149
     */
150
    private float getSoundCategoryVolume(SoundCategory category)
151
    {
152
        return category != null && category != SoundCategory.MASTER ? this.options.getSoundLevel(category) : 1.0F;
153
    }
154
155
    /**
156
     * Adjusts volume for currently playing sounds in this category
157
     */
158
    public void setSoundCategoryVolume(SoundCategory category, float volume)
159
    {
160
        if (this.loaded)
161
        {
162
            if (category == SoundCategory.MASTER)
163
            {
164
                this.sndSystem.setMasterVolume(volume);
165
            }
166
            else
167
            {
168
                for (String s : this.categorySounds.get(category))
169
                {
170
                    ISound isound = (ISound)this.playingSounds.get(s);
171
                    float f = this.getNormalizedVolume(isound, (SoundPoolEntry)this.playingSoundPoolEntries.get(isound), category);
172
173
                    if (f <= 0.0F)
174
                    {
175
                        this.stopSound(isound);
176
                    }
177
                    else
178
                    {
179
                        this.sndSystem.setVolume(s, f);
180
                    }
181
                }
182
            }
183
        }
184
    }
185
186
    /**
187
     * Cleans up the Sound System
188
     */
189
    public void unloadSoundSystem()
190
    {
191
        if (this.loaded)
192
        {
193
            this.stopAllSounds();
194
            this.sndSystem.cleanup();
195
            this.loaded = false;
196
        }
197
    }
198
199
    /**
200
     * Stops all currently playing sounds
201
     */
202
    public void stopAllSounds()
203
    {
204
        if (this.loaded)
205
        {
206
            for (String s : this.playingSounds.keySet())
207
            {
208
                this.sndSystem.stop(s);
209
            }
210
211
            this.playingSounds.clear();
212
            this.delayedSounds.clear();
213
            this.tickableSounds.clear();
214
            this.categorySounds.clear();
215
            this.playingSoundPoolEntries.clear();
216
            this.playingSoundsStopTime.clear();
217
        }
218
    }
219
220
    public void updateAllSounds()
221
    {
222
        ++this.playTime;
223
224
        for (ITickableSound itickablesound : this.tickableSounds)
225
        {
226
            itickablesound.update();
227
228
            if (itickablesound.isDonePlaying())
229
            {
230
                this.stopSound(itickablesound);
231
            }
232
            else
233
            {
234
                String s = (String)this.invPlayingSounds.get(itickablesound);
235
                this.sndSystem.setVolume(s, this.getNormalizedVolume(itickablesound, (SoundPoolEntry)this.playingSoundPoolEntries.get(itickablesound), this.sndHandler.getSound(itickablesound.getSoundLocation()).getSoundCategory()));
236
                this.sndSystem.setPitch(s, this.getNormalizedPitch(itickablesound, (SoundPoolEntry)this.playingSoundPoolEntries.get(itickablesound)));
237
                this.sndSystem.setPosition(s, itickablesound.getXPosF(), itickablesound.getYPosF(), itickablesound.getZPosF());
238
            }
239
        }
240
241
        Iterator<Entry<String, ISound>> iterator = this.playingSounds.entrySet().iterator();
242
243
        while (iterator.hasNext())
244
        {
245
            Entry<String, ISound> entry = (Entry)iterator.next();
246
            String s1 = (String)entry.getKey();
247
            ISound isound = (ISound)entry.getValue();
248
249
            if (!this.sndSystem.playing(s1))
250
            {
251
                int i = ((Integer)this.playingSoundsStopTime.get(s1)).intValue();
252
253
                if (i <= this.playTime)
254
                {
255
                    int j = isound.getRepeatDelay();
256
257
                    if (isound.canRepeat() && j > 0)
258
                    {
259
                        this.delayedSounds.put(isound, Integer.valueOf(this.playTime + j));
260
                    }
261
262
                    iterator.remove();
263
                    logger.debug(LOG_MARKER, "Removed channel {} because it\'s not playing anymore", new Object[] {s1});
264
                    this.sndSystem.removeSource(s1);
265
                    this.playingSoundsStopTime.remove(s1);
266
                    this.playingSoundPoolEntries.remove(isound);
267
268
                    try
269
                    {
270
                        this.categorySounds.remove(this.sndHandler.getSound(isound.getSoundLocation()).getSoundCategory(), s1);
271
                    }
272
                    catch (RuntimeException var8)
273
                    {
274
                        ;
275
                    }
276
277
                    if (isound instanceof ITickableSound)
278
                    {
279
                        this.tickableSounds.remove(isound);
280
                    }
281
                }
282
            }
283
        }
284
285
        Iterator<Entry<ISound, Integer>> iterator1 = this.delayedSounds.entrySet().iterator();
286
287
        while (iterator1.hasNext())
288
        {
289
            Entry<ISound, Integer> entry1 = (Entry)iterator1.next();
290
291
            if (this.playTime >= ((Integer)entry1.getValue()).intValue())
292
            {
293
                ISound isound1 = (ISound)entry1.getKey();
294
295
                if (isound1 instanceof ITickableSound)
296
                {
297
                    ((ITickableSound)isound1).update();
298
                }
299
300
                this.playSound(isound1);
301
                iterator1.remove();
302
            }
303
        }
304
    }
305
306
    /**
307
     * Returns true if the sound is playing or still within time
308
     */
309
    public boolean isSoundPlaying(ISound sound)
310
    {
311
        if (!this.loaded)
312
        {
313
            return false;
314
        }
315
        else
316
        {
317
            String s = (String)this.invPlayingSounds.get(sound);
318
            return s == null ? false : this.sndSystem.playing(s) || this.playingSoundsStopTime.containsKey(s) && ((Integer)this.playingSoundsStopTime.get(s)).intValue() <= this.playTime;
319
        }
320
    }
321
322
    public void stopSound(ISound sound)
323
    {
324
        if (this.loaded)
325
        {
326
            String s = (String)this.invPlayingSounds.get(sound);
327
328
            if (s != null)
329
            {
330
                this.sndSystem.stop(s);
331
            }
332
        }
333
    }
334
335
    public void playSound(ISound p_sound)
336
    {
337
        if (this.loaded)
338
        {
339
            if (this.sndSystem.getMasterVolume() <= 0.0F)
340
            {
341
                logger.debug(LOG_MARKER, "Skipped playing soundEvent: {}, master volume was zero", new Object[] {p_sound.getSoundLocation()});
342
            }
343
            else
344
            {
345
                SoundEventAccessorComposite soundeventaccessorcomposite = this.sndHandler.getSound(p_sound.getSoundLocation());
346
347
                if (soundeventaccessorcomposite == null)
348
                {
349
                    logger.warn(LOG_MARKER, "Unable to play unknown soundEvent: {}", new Object[] {p_sound.getSoundLocation()});
350
                }
351
                else
352
                {
353
                    SoundPoolEntry soundpoolentry = soundeventaccessorcomposite.cloneEntry();
354
355
                    if (soundpoolentry == SoundHandler.missing_sound)
356
                    {
357
                        logger.warn(LOG_MARKER, "Unable to play empty soundEvent: {}", new Object[] {soundeventaccessorcomposite.getSoundEventLocation()});
358
                    }
359
                    else
360
                    {
361
                        float f = p_sound.getVolume();
362
                        float f1 = 16.0F;
363
364
                        if (f > 1.0F)
365
                        {
366
                            f1 *= f;
367
                        }
368
369
                        SoundCategory soundcategory = soundeventaccessorcomposite.getSoundCategory();
370
                        float f2 = this.getNormalizedVolume(p_sound, soundpoolentry, soundcategory);
371
                        double d0 = (double)this.getNormalizedPitch(p_sound, soundpoolentry);
372
                        ResourceLocation resourcelocation = soundpoolentry.getSoundPoolEntryLocation();
373
374
                        if (f2 == 0.0F)
375
                        {
376
                            logger.debug(LOG_MARKER, "Skipped playing sound {}, volume was zero.", new Object[] {resourcelocation});
377
                        }
378
                        else
379
                        {
380
                            boolean flag = p_sound.canRepeat() && p_sound.getRepeatDelay() == 0;
381
                            String s = MathHelper.getRandomUuid(ThreadLocalRandom.current()).toString();
382
383
                            if (soundpoolentry.isStreamingSound())
384
                            {
385
                                this.sndSystem.newStreamingSource(false, s, getURLForSoundResource(resourcelocation), resourcelocation.toString(), flag, p_sound.getXPosF(), p_sound.getYPosF(), p_sound.getZPosF(), p_sound.getAttenuationType().getTypeInt(), f1);
386
                            }
387
                            else
388
                            {
389
                                this.sndSystem.newSource(false, s, getURLForSoundResource(resourcelocation), resourcelocation.toString(), flag, p_sound.getXPosF(), p_sound.getYPosF(), p_sound.getZPosF(), p_sound.getAttenuationType().getTypeInt(), f1);
390
                            }
391
392
                            logger.debug(LOG_MARKER, "Playing sound {} for event {} as channel {}", new Object[] {soundpoolentry.getSoundPoolEntryLocation(), soundeventaccessorcomposite.getSoundEventLocation(), s});
393
                            this.sndSystem.setPitch(s, (float)d0);
394
                            this.sndSystem.setVolume(s, f2);
395
                            this.sndSystem.play(s);
396
                            this.playingSoundsStopTime.put(s, Integer.valueOf(this.playTime + 20));
397
                            this.playingSounds.put(s, p_sound);
398
                            this.playingSoundPoolEntries.put(p_sound, soundpoolentry);
399
400
                            if (soundcategory != SoundCategory.MASTER)
401
                            {
402
                                this.categorySounds.put(soundcategory, s);
403
                            }
404
405
                            if (p_sound instanceof ITickableSound)
406
                            {
407
                                this.tickableSounds.add((ITickableSound)p_sound);
408
                            }
409
                        }
410
                    }
411
                }
412
            }
413
        }
414
    }
415
416
    /**
417
     * Normalizes pitch from parameters and clamps to [0.5, 2.0]
418
     */
419
    private float getNormalizedPitch(ISound sound, SoundPoolEntry entry)
420
    {
421
        return (float)MathHelper.clamp_double((double)sound.getPitch() * entry.getPitch(), 0.5D, 2.0D);
422
    }
423
424
    /**
425
     * Normalizes volume level from parameters.  Range [0.0, 1.0]
426
     */
427
    private float getNormalizedVolume(ISound sound, SoundPoolEntry entry, SoundCategory category)
428
    {
429
        return (float)MathHelper.clamp_double((double)sound.getVolume() * entry.getVolume(), 0.0D, 1.0D) * this.getSoundCategoryVolume(category);
430
    }
431
432
    /**
433
     * Pauses all currently playing sounds
434
     */
435
    public void pauseAllSounds()
436
    {
437
        for (String s : this.playingSounds.keySet())
438
        {
439
            logger.debug(LOG_MARKER, "Pausing channel {}", new Object[] {s});
440
            this.sndSystem.pause(s);
441
        }
442
    }
443
444
    /**
445
     * Resumes playing all currently playing sounds (after pauseAllSounds)
446
     */
447
    public void resumeAllSounds()
448
    {
449
        for (String s : this.playingSounds.keySet())
450
        {
451
            logger.debug(LOG_MARKER, "Resuming channel {}", new Object[] {s});
452
            this.sndSystem.play(s);
453
        }
454
    }
455
456
    /**
457
     * Adds a sound to play in n tick
458
     */
459
    public void playDelayedSound(ISound sound, int delay)
460
    {
461
        this.delayedSounds.put(sound, Integer.valueOf(this.playTime + delay));
462
    }
463
464
    private static URL getURLForSoundResource(final ResourceLocation p_148612_0_)
465
    {
466
        String s = String.format("%s:%s:%s", new Object[] {"mcsounddomain", p_148612_0_.getResourceDomain(), p_148612_0_.getResourcePath()});
467
        URLStreamHandler urlstreamhandler = new URLStreamHandler()
468
        {
469
            protected URLConnection openConnection(final URL p_openConnection_1_)
470
            {
471
                return new URLConnection(p_openConnection_1_)
472
                {
473
                    public void connect() throws IOException
474
                    {
475
                    }
476
                    public InputStream getInputStream() throws IOException
477
                    {
478
                        return Minecraft.getMinecraft().getResourceManager().getResource(p_148612_0_).getInputStream();
479
                    }
480
                };
481
            }
482
        };
483
484
        try
485
        {
486
            return new URL((URL)null, s, urlstreamhandler);
487
        }
488
        catch (MalformedURLException var4)
489
        {
490
            throw new Error("TODO: Sanely handle url exception! :D");
491
        }
492
    }
493
494
    /**
495
     * Sets the listener of sounds
496
     */
497
    public void setListener(EntityPlayer player, float p_148615_2_)
498
    {
499
        if (this.loaded && player != null)
500
        {
501
            float f = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * p_148615_2_;
502
            float f1 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * p_148615_2_;
503
            double d0 = player.prevPosX + (player.posX - player.prevPosX) * (double)p_148615_2_;
504
            double d1 = player.prevPosY + (player.posY - player.prevPosY) * (double)p_148615_2_ + (double)player.getEyeHeight();
505
            double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * (double)p_148615_2_;
506
            float f2 = MathHelper.cos((f1 + 90.0F) * 0.017453292F);
507
            float f3 = MathHelper.sin((f1 + 90.0F) * 0.017453292F);
508
            float f4 = MathHelper.cos(-f * 0.017453292F);
509
            float f5 = MathHelper.sin(-f * 0.017453292F);
510
            float f6 = MathHelper.cos((-f + 90.0F) * 0.017453292F);
511
            float f7 = MathHelper.sin((-f + 90.0F) * 0.017453292F);
512
            float f8 = f2 * f4;
513
            float f9 = f3 * f4;
514
            float f10 = f2 * f6;
515
            float f11 = f3 * f6;
516
            this.sndSystem.setListenerPosition((float)d0, (float)d1, (float)d2);
517
            this.sndSystem.setListenerOrientation(f8, f5, f9, f10, f7, f11);
518
        }
519
    }
520
521
    class SoundSystemStarterThread extends SoundSystem
522
    {
523
        private SoundSystemStarterThread()
524
        {
525
        }
526
527
        public boolean playing(String p_playing_1_)
528
        {
529
            synchronized (SoundSystemConfig.THREAD_SYNC)
530
            {
531
                if (this.soundLibrary == null)
532
                {
533
                    return false;
534
                }
535
                else
536
                {
537
                    Source source = (Source)this.soundLibrary.getSources().get(p_playing_1_);
538
                    return source == null ? false : source.playing() || source.paused() || source.preLoad;
539
                }
540
            }
541
        }
542
    }
543
}
544

Deobfuscated MCP 1.8.9 source of SoundManager from Marcelektro/MavenMCP-1.8.9 (net/minecraft/client/audio/SoundManager.java), stored verbatim.