Creating music player application with Jlayer

Asked

Viewed 516 times

1

I am trying to create a Java application that receives a song through JFileChooser and add this song to a list (ArrayList<File>).

But when accessing the file array.getindex(0).getPath(), the system launches a NullPointerException.

Here is the code:

package br.lp2.view;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.ArrayList;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.*;

import br.lp2.player.*;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import javazoom.jl.player.advanced.AdvancedPlayer;
import br.lp2.main.*;

@SuppressWarnings({ "serial", "unused" })
public class GUI extends JFrame {


    JFileChooser jfile;
    Component parent = null;
    //private Player ply;


    // Dimensoes da tela principal
    private int ALTURA = 300;
    private int LARGURA = 500;

    //Player
    File p1Player;
    ArrayList<File> arrayMusic = new ArrayList<File>();
    private Player pl = null;

    // Janela de cadastro de usuario
    private CadastroUsuario cadastroUsuario = new CadastroUsuario();

    // Menu bar
    private JMenuBar menuBar = new JMenuBar();
    // Menus
    private JMenu menuMusicas = new JMenu("Musicas");
    private JMenu menuPlaylists = new JMenu("Playlists");
    private JMenu menuUsuarios = new JMenu("Usuarios");
    // Menu items
    private JMenuItem adicionarMusica = new JMenuItem("Adicionar musica");
    private JMenuItem removerMusica = new JMenuItem("Remover musica");
    private JMenuItem verMusicas = new JMenuItem("Ver lista de musicas");
    private JMenuItem verPlaylists = new JMenuItem("Ver playlists");    
    private JMenuItem criarPlaylist = new JMenuItem("Criar playlist");
    private JMenuItem removerPlaylist = new JMenuItem("Remover playlist");
    private JMenuItem verUsuarios = new JMenuItem("Ver lista de usuarios");
    private JMenuItem adicionarUsuario = new JMenuItem("Cadastrar        usuarios");
    private JMenuItem removerUsuario = new JMenuItem("Remover usuario");

    // Botoes
    private JButton play = new JButton("Play");
    private JButton pause = new JButton("Pause");
    private JButton proximaMusica = new JButton(">>");
    private JButton anteriorMusica = new JButton("<<");

    public GUI() {
        jfile = new JFileChooser();

        // Configuracoes padrao
        setTitle("Player de musica");
        setSize(LARGURA, ALTURA);
        setLayout(null);
        setVisible(true);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Adicionando menu
        menuBar.add(menuMusicas);
        menuBar.add(menuPlaylists);
        menuBar.add(menuUsuarios);
        // Adicionando itens aos menus
        menuMusicas.add(verMusicas);
        menuMusicas.add(adicionarMusica);
        menuMusicas.add(removerMusica);
        menuPlaylists.add(verPlaylists);
        menuPlaylists.add(criarPlaylist);
        menuPlaylists.add(removerPlaylist);
        menuUsuarios.add(verUsuarios);
        menuUsuarios.add(adicionarUsuario);
        menuUsuarios.add(removerUsuario);
        // Setando menubar
        setJMenuBar(menuBar);

        // Adicionando botoes
        add(play);
         add(pause);
        add(proximaMusica);
        add(anteriorMusica);
        // Setando posicao dos botoes
        play.setBounds(70, ALTURA - 90, 100, 30);
        pause.setBounds(180, ALTURA - 90, 100, 30);
        proximaMusica.setBounds(290, ALTURA - 90, 50, 30);
    anteriorMusica.setBounds(10, ALTURA - 90, 50, 30);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    pause.setEnabled(false);
    // Login inicial
    // Login login = new Login();       

    // Eventos
    adicionarMusica.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            jfile.showOpenDialog(parent);
            p1Player = jfile.getSelectedFile(); 
            try{
                arrayMusic.add(p1Player);
            }catch (NullPointerException ex){
                System.out.println(ex.getMessage());
                System.out.println(ex.getStackTrace());
            }
        }
    });

    play.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            pause.setEnabled(true);
            play.setEnabled(false);
            Music msc = new Music();
            msc.start();

        }
    });         
    pause.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            play.setEnabled(true);
        }
    });

    adicionarUsuario.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cadastroUsuario.setVisible(true);               
        }
    });
}

/*class Music extends Thread implements Runnable{
    public void run(File file_t) throws FileNotFoundException{
        System.out.println("chegou aqui");
        FileInputStream input = new FileInputStream(file_t);
        PlayerFile ply = new PlayerFile(file_t);
        Thread playing = new Thread((Runnable) ply);
        playing.run();
    }
}*/
class Music extends Thread{
    public void run(){
        try {
        System.out.println("chegou aqui222");
        //System.out.println("CAMINHO " + arrayMusic.get(0).getPath());
        InputStream teste = this.getClass().getResourceAsStream("C:/Users/pedrohbcavalcante/Downloads/ateste.mp3");
        //System.out.println("GETPATH() " + file.getPath() + " GETABSOLUTPATH() "+ file.getAbsolutePath());
            pl = new Player(teste);
            pl.play();
        } catch (JavaLayerException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}
}

Resulted me in the following stacktrace:

Exception in thread "Thread-3" java.lang.NullPointerException: in
    at javazoom.jl.decoder.Bitstream.<init>(Unknown Source)
    at javazoom.jl.player.Player.<init>(Unknown Source)
    at javazoom.jl.player.Player.<init>(Unknown Source)
    at br.lp2.view.GUI$Music.run(GUI.java:174)
  • Hello Pedro, could you edit the question and include the stack trace? It would also be interesting to simplify your example (see that other users do not have classes like CadastroUsuario, getting hard to run your code to try to reproduce the problem).

  • Hello Anthony, I made a change to call the Music class through . start() and resulted in the stack that is on Edit. When it comes to the User Register class, it’s just another part of the project where it’s more linked to the view. It’s just something to comment on, as it’s already there. Thanks for the help :)

1 answer

1


The NullPointerException is coming from the class builder Bitstream. That is to say, from here.

According to the source code of the class BitStream:

    public Bitstream (InputStream in) {
        if (in == null) throw new NullPointerException("in");

That is, the parameter in passed to the builder was null.

Going up the stacktrace we have the constructor of the class Player. This class no longer exists in the most current version of Jlayer-gdx. However, looking at the previous version, this class existed. Looking at in the commit code where it was removed, we have it:

public Player(InputStream stream) throws JavaLayerException
{
    this(stream, null); 
}

public Player(InputStream stream, AudioDevice device) throws JavaLayerException
{
    bitstream = new Bitstream(stream);

That is, the parameter stream was void.

Further up the stacktrace, we come to that line of your code:

            pl = new Player(teste);

That is to say, teste was null. This variable has its value assigned here:

        InputStream teste = this.getClass().getResourceAsStream("C:/Users/pedrohbcavalcante/Downloads/ateste.mp3");

And that’s wrong! The getResourceAsStream(...) returns null when no resource is found.

Why didn’t he find the resource? Because the method getResourceAsStream(...) serves to search for resources within the JAR (or WAR or EAR) file that contains your application. However, this is not your case, the resource is not inside the JAR, but directly in the file system.

The solution would be to use something like this:

        InputStream teste = new FileInputStream("C:/Users/pedrohbcavalcante/Downloads/ateste.mp3");

When using the FileInputStream, the resource will be searched within the file system. The compiler will complain that a IOException, which is what is launched if you ocrrer an error while trying to locate the file (possibly FileNotFoundException, which is the subclass of IOException, in case the file does not exist). So put one more catch to the IOException.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.