Here is my Sound class (im completely clueless of what all this stuff means).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| class Sound{ private AudioFileFormat baseFileFormat; private AudioFormat baseFormat,decodedFormat; private AudioInputStream din,in; private AudioFileFormat.Type type; private float frequency; public Sound(String filename){ try{ baseFileFormat = AudioSystem.getAudioFileFormat(new File(filename)); } catch(UnsupportedAudioFileException ex){ System.out.println("Audio File not Supported"); } catch(IOException ex2){} baseFormat = baseFileFormat.getFormat(); type = baseFileFormat.getType(); frequency = baseFormat.getSampleRate(); in=null; try{ in= AudioSystem.getAudioInputStream(new File(filename)); } catch(UnsupportedAudioFileException ex){} catch(IOException ex2){} din = null; baseFormat = in.getFormat(); decodedFormat =new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); din = AudioSystem.getAudioInputStream(decodedFormat, in); } public void play(){ try{ rawplay(decodedFormat, din); } catch(LineUnavailableException ex){} catch(IOException ex2){} } public void stop(){ try{ in.close(); } catch(IOException ex2){} } private void rawplay(AudioFormat targetFormat,AudioInputStream din) throws IOException, LineUnavailableException{ byte[] data = new byte[4096]; SourceDataLine line = getLine(targetFormat); if (line != null){ line.start(); int nBytesRead = 0, nBytesWritten = 0; while (nBytesRead != -1){ nBytesRead = din.read(data, 0, data.length); if (nBytesRead != -1) nBytesWritten = line.write(data, 0, nBytesRead); } line.flush(); line.stop(); line.close(); din.close(); } } private SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException{ SourceDataLine res = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); res = (SourceDataLine) AudioSystem.getLine(info); res.open(audioFormat); return res; } } |
When i try playing a sound with it, the game freezes untill the sound stops playing. When i try playing it again, it wont play. The stop() function does not stop the sound. I have another question: how would i implement loop() function (one that works properly). To make long story short: is there a library-thingy for a java application which provides play(), stop() and loop() functions?
