Try to make a music player using Basic Player

Introduction

This article is the 13th day article of SLP KBIT Advent Calendar 2019. (~~ Sliding safe ~~ I'm sorry it was out ...) You have finally reached the turning point!

This time, I will use the "BasicPlayer API" to create a music player that I've always wanted to make. Eclipse is the Java application development, but this time we will use the VS Code extension "Java Extension Pack" for development.

The source code is released on GitHub for the time being, but it has only simple functions and is in the middle of the process, so I would like to update it in the future. https://github.com/kakukaku-15/media_player

Development environment

API used

Preparation

Java environment construction

First, download ** JDK ** from https://www.oracle.com/java/technologies/javase-jdk15-downloads.html. *** JDK **: A package that integrates the software required for software development in Java. スクリーンショット 2020-12-13 22.43.26.png

After the download is complete, open the .dmg file, launch the installer, and follow the installer's instructions to complete the installation.

Next, install the VS Code extension "** Java Extension Pack **" to develop Java applications with VS Code. Java Extension Pack

Download BasicPlayer API

BasicPlayer is an API with simple functions that is threaded based on the JavaSound API. You can play audio files such as MP3s.

Download ** BasicPlayer API ** from http://www.javazoom.net/jlgui/api.html. The following is the contents of the downloaded directory. BasicPlayer API

Project creation

Open VSCode, select Java: Create Java Project ...-> No build tools from the command palette, and specify the project name to create the project.

Then, the directories src and lib will be created automatically. Place all the .jar files in the basicplayer3.0.jar and lib directories directly under the BasicPlayer3.0 downloaded above in the lib of the project you created.

Now you are ready. Write the source code directly under the src directory.

File structure

media_player
├── README.md
├── lib
│   ├── basicplayer3.0.jar
│   ├── commons-logging-api.jar
│   ├── jl1.0.jar
│   ├── jogg-0.0.7.jar
│   ├── jorbis-0.0.15.jar
│   ├── jspeex0.9.7.jar
│   ├── mp3spi1.9.4.jar
│   ├── tritonus_share.jar
│   └── vorbisspi1.0.2.jar
└── src
    ├── Player.java
    └── SimplePlayer.java

development of

Here is what was actually made. It's very simple, but I think it has the minimum functionality that can be called a music player.

実行結果

As a function, when you press the load button, a dialog is displayed, and you can load an audio file (.mp3) by specifying the file path. When imported, the file name will be displayed in the center of the window as shown in the picture. Press the play button to play the music. It is also possible to pause and resume from the stop position.

The completed source code is as follows.

SimplePlayer.java


package src;

import java.io.*;
import java.util.Map;
import javazoom.jlgui.basicplayer.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class SimplePlayer extends JFrame implements ActionListener, BasicPlayerListener {
    //Object creation
    JFrame frame = new JFrame();
    JFileChooser chooser = new JFileChooser();
    BasicPlayer player = new BasicPlayer();
    BasicController control = (BasicController) player;
    File playFile;
    JButton btnOpen, btnPlay;
    JLabel label;

    //constructor
    SimplePlayer() {
        frame.setTitle("MP3 Player"); //title
        frame.setLayout(new BorderLayout());
        // display("" + player.getStatus());

        //Generate button
        btnOpen = new JButton("Read"); //Open button
        btnOpen.setActionCommand("open");
        btnOpen.addActionListener(this);

        btnPlay = new JButton("Regeneration"); // Regenerationボタン
        btnPlay.setActionCommand("play/pause");
        btnPlay.addActionListener(this);

        label = new JLabel("Set Music");
        label.setHorizontalAlignment(JLabel.CENTER); //Displayed in the center

        //Module installation
        frame.add(btnOpen, BorderLayout.NORTH); //Set the open button
        frame.add(btnPlay, BorderLayout.SOUTH); //Set the open button
        frame.add(label, BorderLayout.CENTER); //Character string display

        // frame.pack(); //Layout auto-optimization
        frame.setSize(200, 200); //Window size setting
        frame.setVisible(true); //Set window visibility

        //Reflect player settings
        player.addBasicPlayerListener(this);

        //Processing when closing a window
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0); //End
            }
        });

    }

    //Regeneration
    public void play() {
        try {
            //Play file, set volume, pan, etc.
            control.play();
            // display(control.toString());
            control.setGain(0.50);
            control.setPan(0.0);
        } catch (BasicPlayerException e) {
            e.printStackTrace();
        }
    }

    //pause
    public void pause() {
        try {
            control.pause();
        } catch (BasicPlayerException e) {
            e.printStackTrace();
        }
    }

    //Resume
    public void resume() {
        try {
            control.resume(); //Play from where you paused
        } catch (BasicPlayerException e) {
            e.printStackTrace();
        }
    }

    //Control Basic Player through controller
    public void setController(BasicController controller) {
        display("Controll: " + controller.toString());
    }

    //Get current status such as volume, pan, player playback, etc.
    public void stateUpdated(BasicPlayerEvent event) {
        display("stateUpdated: " + event.toString());
    }

    //Get sound progress
    public void progress(int read, long time, byte[] data, Map map) {
        // display("progress :" + map.toString());
        // display("" + player.getStatus());
    }

    //Get details of opened sound file
    public void opened(Object object, Map map) {
        display("opened :" + map.toString());
    }

    //Output string to console
    public void display(String str) {
        if (str != null)
            System.out.println(str);
    }

    //Button action
    public void actionPerformed(ActionEvent event) {
        if (event.getActionCommand() == "open") { // open
            int choice = chooser.showOpenDialog(this);
            try {
                if (choice == JFileChooser.APPROVE_OPTION) {
                    playFile = chooser.getSelectedFile(); //Get the path of the selected file
                    FileReader fr = new FileReader(playFile); //Read from file path
                    // frame.setTitle(playFile.getName()); //Rename the title to the selected file
                    label.setText(playFile.getName()); //Show the name of the selected file
                    fr.close(); //File release

                    //Open the specified sound file
                    control.open(playFile);
                }
            } catch (Exception e) {
                display("Failed to expand the file dialog.");
            }
        } else if (event.getActionCommand() == "play/pause") {
            switch (player.getStatus()) {
                case BasicPlayer.OPENED: //Regeneration
                    play();
                    display("Regeneration");
                    btnPlay.setText("pause");
                    break;
                case BasicPlayer.PLAYING: //pause
                    pause();
                    display("pause");
                    btnPlay.setText("Regeneration");
                    break;
                case BasicPlayer.PAUSED: //Resume
                    resume();
                    display("Resume");
                    btnPlay.setText("pause");
                    break;
                default:
                    break;
            }
        }
    }
}

In main, generate the created SimplePlayer instance and display the screen.

Player.java


package src;

//Player's main class
public class Player {
    public static void main(String[] args) {
        new SimplePlayer();
    }
}

Summary

I made a simple music player using BasicPlayer. I'm glad I made it easier than I expected.

However, the challenges are piled up. I could only play MP3s, but I would like to be able to play other audio files and finally videos as well. As other functions, I would like to implement playlist creation and playback position adjustment. I think we need to think more about the UI. I want to be a person who has more planning and can do it steadily.

reference

--Java environment construction (Mac version) JDK installation https://techfun.cc/java/mac-jdk-install.html

--Build a Java development environment with VS Code https://www.suzu6.net/posts/130-vscode-for-java/

--Super simple player using Swing and javazoom's Basic Player API http://yasshiemd.web.fc2.com/sub/appli/simpleplayer/simpleplayer.html

Recommended Posts

Try to make a music player using Basic Player
Try to make a simple callback
Try to make a peepable iterator
How to make an crazy Android music player
Try to make a timeline report of method execution time using JFR API
Try to build a Java development environment using Docker
Make a rhombus using Java
[Beginner] Try to make a simple RPG game with Java ①
I tried using Hotwire to make Rails 6.1 scaffold a SPA
How to make a Java container
How to make a JDBC driver
How to make a splash screen
How to make a Jenkins plugin
[Java] Try to implement using generics
How to make a Maven project
Try to create a server-client app
CompletableFuture Getting Started 2 (Try to make CompletableFuture)
How to make a Java array
How to make a hinadan for a Spring Boot project using SPRING INITIALIZR
Try to make a cross-platform application with JRuby (jar file generation)
[Unity] I tried to make a native plug-in UniNWPathMonitor using NWPathMonitor
Try to make a CS 3D tile from the Geographical Survey tile
How to make a groundbreaking diamond using Java for statement wwww
Interface Try to make Java problem TypeScript 7-3
How to execute a contract using web3j
I tried to make a simple face recognition Android application using OpenCV
How to sort a List using Comparator
How to make a Java calendar Summary
Try to display a slightly rich Webview in Swift UI using UIViewRepresentable
[Basic] How to write a Dockerfile Self-learning ②
The road to creating a music game 2
Try to issue or get a card from Jave to Trello using API
Java beginner tried to make a simple web application using Spring Boot
Try to create a browser automatic operation environment using Selenide in 5 minutes
I tried to make a talk application in Java using AI "A3RT"
How to make asynchronous pagenations using Kaminari
The road to creating a music game 3
The road to creating a music game 1
I tried to make Basic authentication with Java
Make a margin to the left of the TextField
I did Java to make (a == 1 && a == 2 && a == 3) always true
Try to create a bulletin board in Java
How to play audio and music using javascript
[Ethereum] How to execute a contract using web3j-Part 2-
Increment behavior Try to make Java problem TypeScript 3-4
Let's make a shopping site using stripe! (Purchase)
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
String operation Try to make Java problem TypeScript 9-3
(Android) Try to display static text using DataBinding
How to make a lightweight JRE for distribution
Try to display prime numbers using boolean type
How to generate a primary key using @GeneratedValue
How to make a follow function in Rails
I tried to implement a server using Netty
Try using Maven
Try using powermock-mockito2-2.0.2
Try using GraalVM
Try using jmockit 1.48
When making a personal app, I was wondering whether to make it using haml
Try using sql-migrate
[Introduction] Try to create a Ruby on Rails application