javaaudiojavasound

How can i create a class that has a function takes in a string input as filename and then plays a soundfile?


This code checks if the goblin is in the same position as a coin and then gives it points. It should also play a sound when a coin is picked up

            if (goblin.getPos().equals(coin.getPos())) {
            if (goblinTarget == coin) {
                targetCheck = true;
            }
            // give goblin some points for picking this up
            goblin.addScore(100);
            collectedCoins.add(coin);
            coinsInPlay = coinsInPlay - 1;
            // play sound
            SoundPlayer.playSound("pickCoin");
            // SoundPlayer would be the class that has a function playSound() 
            
            
        }

Solution

  • try this

    if (goblin.getPos().equals(coin.getPos())) {
            if (goblinTarget == coin) {
                targetCheck = true;
            
            // give goblin some points for picking this up
            goblin.addScore(100);
            collectedCoins.add(coin);
            coinsInPlay = coinsInPlay - 1;
    
            // play sound
            File lol = new File("somesound.wav");//replace somesound.wav with your own desired audio file
            try{
                Clip clip = AudioSystem.getClip();
                clip.open(AudioSystem.getAudioInputStream(lol));
                clip.start();
               } catch (Exception e){
                    e.printStackTrace();
               }
            } 
        }