我怎样才能创建一个 class 函数,它接受一个字符串输入作为文件名,然后播放一个声音文件?

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

此代码检查妖精是否与硬币处于相同位置,然后给它分数。 它也应该在捡起硬币时播放声音

            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() 
            
            
        }

试试这个

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();
           }
        } 
    }