我正在尝试将音乐文件导入到我的程序中,但也允许它在启动时在其中两个中随机选择。我使用URL系统进行导入,因此我有一个名为soundResource的变量来完成此任务。

但是,每当我尝试运行它时(使用Eclipse,尽管我不认为这会导致错误),程序均会失败,说明

soundResource cannot be resolved to a variable

我在其他主题中没有看到过与此相关的内容,尤其是它与变量的范围有关。我如何在下面修复此代码,以使变量彼此可见?

适用代码:
package Tetris;

//import java.io.InputStream;

import java.net.URL;
import java.util.Random;
import javax.sound.sampled.*;

public class Audio {
    Random rand = new Random();
    Boolean RandomSongNum = rand.nextBoolean();
    AudioInputStream ais;
    Clip clip;

    public Audio () {};

    public void playAudio () throws Exception {
        //open the sound file as a Java input stream
        //The Starter music file
        if(RandomSongNum){
            URL soundResource = this.getClass().getClassLoader().getResource("BH-Lightest.wav");
        } else {
            URL soundResource = this.getClass().getClassLoader().getResource("RY-Lightest.wav");
        }

        //Set audio path to within java file
        AudioInputStream in = AudioSystem.getAudioInputStream(soundResource); <<<--- Error occurs here

        clip = AudioSystem.getClip();

        clip.open(in);
        clip.loop(Clip.LOOP_CONTINUOUSLY);  //get the file to loop continuously

    }

    public void playAudioMed () throws Exception {
        //open the sound file as a Java input stream
        //Medium score music file
        if (RandomSongNum) {
            URL soundResource = this.getClass().getClassLoader().getResource("BH-Light.wav");
        } else {
            URL soundResource = this.getClass().getClassLoader().getResource("RY-Light.wav");
        }

        //Set audio path to within java file
        AudioInputStream in = AudioSystem.getAudioInputStream(soundResource); <<<--- Error occurs here

        clip = AudioSystem.getClip();

        clip.open(in);
        clip.loop(Clip.LOOP_CONTINUOUSLY);  //get the file to loop continuously

    }

    public void playAudioHi () throws Exception {
        //open the sound file as a Java input stream
        //High Score Music File
        if(RandomSongNum) {
            URL soundResource = this.getClass().getClassLoader().getResource("BH.wav");
        } else {
            URL soundResource = this.getClass().getClassLoader().getResource("RY.wav");
        }

        //Set audio path to within java file
        AudioInputStream in = AudioSystem.getAudioInputStream(soundResource); <<<--- Error occurs here

        clip = AudioSystem.getClip();

        clip.open(in);
        clip.loop(Clip.LOOP_CONTINUOUSLY);  //get the file to loop continuously

    }

    public void stopAudio() {
        clip.stop();
    }



}

最佳答案

该变量在if块中声明,因此仅在if范围内。因此,您以后不能在代码中引用它。将声明移至if之前进行修复。

URL soundResource;
if(RandomSongNum){
    soundResource = this.getClass().getClassLoader().getResource("BH-Lightest.wav");
} else {
    soundResource = this.getClass().getClassLoader().getResource("RY-Lightest.wav");
}

07-24 09:52
查看更多