Quantcast
Channel: Форум программистов и сисадминов Киберфорум
Viewing all articles
Browse latest Browse all 514808

Ошибка NullPointerException в Thread-2 - Java SE (J2SE)

$
0
0
В моей программе появляется ошибка
java.lang.NullPointerException
at ru.exulw0lf.game.sticks_r2.Sound.setVolume(Sound.java:158)
at ru.exulw0lf.game.sticks_r2.Enter.main(Enter.java:50)
at ru.exulw0lf.game.sticks_r2.Enter.launch(Enter.java:13)
at ru.exulw0lf.game.sticks_r2.Main.main(Main.java:29)

Я понял, что вызываю нулевую переменную, знаю где, но не понимаю почему она вдруг становится нулевой. в строке Sound.java:65 раньше тоже было, но я прописал path в вызов переменной и вроде заработало, а сейчас не получается

:

package ru.exulw0lf.game.sticks_r2;

import org.apache.log4j.*;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;

public class Main {
    static Logger log = LogManager.getLogger(Main.class);
    static boolean wannaPlay = false;

    static String[] arg = new String[1];
    public static void main(String[] args)
            throws InterruptedException, UnsupportedAudioFileException,
            LineUnavailableException, IOException {
        try {
            log.info("-----------------------------------Starting " +
                    "programm---------------------------------");
            //arg = args;
            arg[0] = "/home/exulw0lf/IdeaProjects/Sticks_r2/NewFolder/sourses/music/Daemon.wav";
            Sound sound = new Sound();
            Enter enter = new Enter();
        /*String p3 = sound.getClass().getResource(path).getPath();
//      эквиваленто
        Class<? extends Sound> p1 = sound.getClass();
        URL p2 = p1.getResource("");
        String p3 = p2.getPath();*/
            Enter.launch();
            sound.start();
        } catch (NullPointerException e) {
            log.fatal("Some variable is equals null!",e);
        }
        log.info("-----------------------------------Ending " +
                "programm-----------------------------------");
    }

    public static void launch() {
        while (true) {
            System.out.println("Музыка в фоне!");
            try {
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}// 380 строк кода


:

package ru.exulw0lf.game.sticks_r2;

import org.apache.log4j.*;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Sound extends Thread{
    static Logger log = LogManager.getLogger(Main.class);

    public File soundFile = null;
    AudioInputStream ais = null;
    double[] soundVolumes = new double[101];
    Clip clip = null;
    long clipLength = 0;
    FloatControl volume = null;
    boolean isPlaying = false;
    long timeOfBegin = 0;
    boolean musicMain = false;
    String path = null;

    public static void main(String[] args)
            throws InterruptedException, UnsupportedAudioFileException,
            LineUnavailableException, IOException{

        Sound sound = new Sound();
        String path = null;
        try {
            path = args[0] + "/music/Daemon.wav"; // сам берёт адрес папки где находится
            log.info("Its a terminal launch");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Запуск не из консоли!\n\n");
            path = "/home/exulw0lf/IdeaProjects/Sticks_r2/NewFolder/sourses/music/Daemon.wav";
            log.info("Its a IntellijIDEA launch");
        }catch (NullPointerException e) {
            System.out.println("Запуск не из консоли!\n\n");
            path = "/home/exulw0lf/IdeaProjects/Sticks_r2/NewFolder/sourses/music/Daemon.wav";
        }
        //sound.startAudio(true);
    }

    public void selectAudio() {
        try {
            soundFile = new File(path);
            // создаём объект файла
            ais = AudioSystem.getAudioInputStream(soundFile);
            // создаём звуковой поток
            clip = AudioSystem.getClip();
        } catch (UnsupportedAudioFileException e) {
            log.error("Unsupported audio file", e);
        } catch (IOException e) {
            log.error("Unsupported AudioInputStream", e);
        } catch (LineUnavailableException e) {
            log.error("Unsupported Clip", e);
        }
    }

    public void startAudio(String s, boolean m)
            throws IOException, UnsupportedAudioFileException,
            LineUnavailableException, InterruptedException {
        path = s;
        musicMain = m; // до этого шага path был, а тут его нет
        //теперь пофикшено, но вылетает на строке 158
        selectAudio();
        clip.open(ais); // открываем файл
        clipLength = clip.getMicrosecondLength()/1000; // длинна песни в мсек
        volume = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
        // созд. объект упр-ия звуком
        while (musicMain) {
            playPrimary();
        }
        clip.close();
    }

    public void holdOn() {
        if (!isPlaying) {
            clip.stop();
        } else {
            log.warn("Clip is already paussed!");
        }
    }

    public void moveOn() {
        if (isPlaying) {
            clip.start();
        } else {
            System.out.println("Клип уже остановлен!");
            log.warn("Clip is already continued!");
        }
    }

    public void playPrimary() throws InterruptedException {
        if (!isPlaying) {
            isPlaying = true;
            clip.setFramePosition(0); // ставим музыку на начало
            clip.start();// запускаю песню
            timeOfBegin = getCurrentTime();
            setVolume(30);
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                private int counter = 0;
                public void run() {
                    //System.out.println("Check time > " + counter++);
                    if (timeOfBegin + clipLength < getCurrentTime()) {  // 1/4 клипа
                        System.out.println("End of song");
                        holdOn();
                        System.out.println("So we'll start again");
                        timeOfBegin = getCurrentTime();
                        clip.setFramePosition(0); // ставим музыку на начало
                        clip.start(); // запускаю песню
                        moveOn();
                        counter = 0;
                    }
                }
            }, 0, 2500);  // period sound+2sec
            timeOfBegin = getCurrentTime();
            //System.out.println(timeOfBegin);
        }
    }

    public long getCurrentTime() {
        Date time = new Date();
        return time.getTime();
    }

    public void volume() {
        // созд. массив, переводящий проценты в звук. шкалу
        soundVolumes[0] = -80;
        for (int i = 1; i < 101; i++) {
            double zzz = (-60 + i * 0.660406);
            soundVolumes[i] = zzz;
        }
    }

    @Override
    public void run() {
        Main main = new Main();
        path = main.arg[0];
        //System.out.println("Запуск фоновой музыки");
        Sound sound = new Sound();
        try {
            sound.startAudio(path, true);
        } catch (UnsupportedAudioFileException e) {
            log.error("Unsupported audio file", e);
        } catch (IOException e) {
            log.error("Unsupported AudioInputStream", e);
        } catch (LineUnavailableException e) {
            log.error("Unsupported Clip", e);
        } catch (InterruptedException e) {
            log.error("Cannot sleep of main thread");
        }
    }

    public void setVolume(int i) {
        volume.setValue((float) soundVolumes[i]);
        //вот тут вылетает
    }
}




:

package ru.exulw0lf.game.sticks_r2;

import org.apache.log4j.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Enter {
    static Logger log = LogManager.getLogger(Main.class);

    public static void launch() {
        while (true) {
            main();
        }
    }

    public static void main() {
        try {
            Out.clear(0);
        } catch (InterruptedException e) {
            log.error(e);
        }
        System.out.println("Выберите действие, которое вы хотите применить: ");
        System.out.println("1. Включить музыку");
        System.out.println("2. Приостановить музыку");
        System.out.println("3. Продолжить музыку");
        System.out.println("4. Изменить громкость");
        System.out.println("5. Выбрать другую музыку (*.wav)");
        System.out.println("6. Выход из программы");
        System.out.print("\nВыбор >> ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String choise = null;
        Sound sound = new Sound();
        Main main = new Main();
        try {
            choise = br.readLine();
        } catch (IOException e) {
            log.error("Cannot read from terminal", e);
        }
        if (choise.equals("1")) { // add try&catch
            sound.start();
        } else if (choise.equals("2")) {
            sound.holdOn();
        } else if (choise.equals("3")) {
            sound.moveOn();
        } else if (choise.equals("4")) {
            System.out.print("Введите громкость от 1 до 100:");
            try {
                int vol = br.read();
                sound.setVolume(vol);
            } catch (IOException e) {
                log.error("Cannot read from terminal", e);
            }
        } else if (choise.equals("5")) {
            String path = null;
            try {
                path = br.readLine();
            } catch (IOException e) {
                log.error("Cannot read from terminal", e);
            }
            sound.selectAudio();
        } else if (choise.equals("6")) {
            System.out.println("Bye bye!");
            try {
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                log.error("Cannot sleep of main thread");
            }
            System.exit(0);
        }
    }
}


Viewing all articles
Browse latest Browse all 514808

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>