- How to Play Mp3 File in Java Tutorial | Simple Steps
- How to Play Mp3 File in Java
- Downloading jlayer Jar File
- Adding jlayer Jar File to Our Project
- Preparing Display for Our Music Player
- Using music in a java program
- Using music in a java program
- How to play music in Java (Simple)
- Java Music: Javan Radio Music
- Java Tutorial — Add music/sound to java
- How to play music in javascript
- How to play music in java
- how to add music to java
- Воспроизведение звука в Java
- Воспроизведение звука
- Упрощаем процесс
- Форматы
How to Play Mp3 File in Java Tutorial | Simple Steps
Hello friends, welcome to my other tutorial, and in this tutorial, you will learn about How to Play Mp3 File in Java . Most of us like to listen to music, and nothing could be more pleasing to us if we can make and customize our Music player. By going through this article, you will get to know how you can play an mp3 file in Java and also you will create a simple music player.
I am going to use Intellij IDEA IDE for the programming development, but you are free to use any IDE like NetBeans or Eclipse. In any case, if you want to download the source code of the program, then the link of the file is given at the end of the tutorial.
So let’s start our tutorial How to Play Mp3 File in Java and learn step by step.
How to Play Mp3 File in Java
Downloading jlayer Jar File
- To play any mp3 file in java, you need to download a jar file called jlayer and add it to your java project.
- To download the jlayer jar file, you can simply click on the link given below.
- After downloading the jlayer jar file, the next thing you have to do is to add it to your project.
Adding jlayer Jar File to Our Project
- Create a new Java project in your IDE and give it a name. You can use any IDE like NetBeans, Eclipse or IntelliJ IDEA to create your Java project.
- For NetBeans users,
- Right click on the Libraries folder then select Add JAR/Folder and then you can add the JAR file to your project.
- Right click on the Project then select Properties —>>>>Java Build Path and then you can choose Add External JARs button to add the JAR file.
- Go to File––>>>>Project Structure—>>>>Libraries then click on the “+” sign and select Java and then you can add the JAR file.
Preparing Display for Our Music Player
- Create a class(MusicPlayer in this example).
- Now create an object of the JFrame class and set some of its properties like its Title, Background color, its Layout, its Size and Location and its Default Close Operation.
- Now create an object of five JButtons(Select Mp3, Play, Pause, Resume and Stop) and one JLabel( songNameLabel).
- Now you have to set the size and location of JButtons and JLabel using the setBounds() method and then finally you have to add them to the JFrame using the add() method.
- Program is given below.
Using music in a java program
One work-around might be to use JMF instead, as suggested, if you want looping to work for large files anyway. my mp3 file alarm.mp3 Solution 1: You can play a song like that : Check this related topic Solution 2: Call the play from the method: how to add music to java
Using music in a java program
I was trying out the method of creating a background music for a java program, but it displayed an IO excedption error when i clicked the play button.
package javaentertainment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileInputStream; import java.io.IOException; import javax.swing.*; import sun.audio.AudioData; import sun.audio.AudioPlayer; import sun.audio.AudioStream; public class Music < public static void main(String args[]) < JFrame frame=new JFrame(); frame.setSize(100,100); JButton button=new JButton("P L A Y"); frame.add(button); button.addActionListener(new AL()); frame.show(); >public static class AL implements ActionListener < public void actionPerformed(ActionEvent e) < music(); >> public static void music() < AudioPlayer MGP=AudioPlayer.player; AudioStream BGM; AudioData MD; ContinousAudioDataStream loop=null; try < BGM = new AudioStream(new FileInputStream("Vision.wmv")); MD=BGM.getData(); loop=new ContinousAudioDataStream(MD); >catch (IOException ex) < System.out.println(ex); >MGP.start(loop); // word loop was underlined by netbeans > >
When I run the program and click on play it displays the following error, java.io.IOException: could not create audio stream from input stream
You should use JMF (Java Media Framework). For your interest: The list of accepted formats can be found here.
In short, it supports AIFF, AVI, GSM, MVR, MID, MPG, MP2, MOV, AU and WAV files.
But there is a workarond as stated here:
On a side note, if you add a mime-setting in JMFRegistry to map Windows Media content (such as .asf and .wmv) to the content-type «video/mpeg», JMF can actually play Windows Media or any other DirectShow file (and only file — http wont work).
I would be surprised if Java can hand Windows Media format samples — try converting the .wmv to a .wav file and see if it works then.
java.io.IOException: could not create AudioData object
Appears from the source [1] that this means that «your audio file is size > 1 MB» and it doesn’t like that for whatever reason. Maybe a bug [?] that they don’t accomodate for this.
One work-around might be to use JMF instead, as suggested, if you want looping to work for large files anyway.
Java — How to make musical note sounds?, Browse other questions tagged java or ask your own question. The Overflow Blog WSO2 joins Collectives™ on Stack Overflow. C#: IEnumerable, yield return, and lazy evaluation. Featured on Meta Announcing the arrival of Valued Associate #1214: Dalmarus. Testing new traffic management tool. Ask Wizard …
How to play music in Java (Simple)
this tutorial doesn’t work on jdk 9 or above!the following link will take you to a tutorial that will work on jdk 9 or above: https:// www .youtube. com /watch?v
Java Music: Javan Radio Music
Download Now !! https://play.google.com/store/apps/details?id=com.tmxdigital.javamusicJava Music, Javan Radio musicListen to the best Java Music stations, J
Java Tutorial — Add music/sound to java
This tutorial will show you how to add background music or a sound file to your Java program. The » music » method I made in this program can be used to play …
How to play music in javascript
Hello there I have a html5 desktop push notification written in javascript and when that notification comes up I want to play a sound affect so that the user knows there is a notification for them to look at
function notifyMe() < if (!("Notification" in window)) < alert("This browser does not support system notifications"); >else if (Notification.permission === "granted") < notify(); >else if (Notification.permission !== 'denied') < Notification.requestPermission(function (permission) < if (permission === "granted") < notify(); >>); > function notify() < var notification = new Notification('TITLE OF NOTIFICATION', < icon: 'http://carnes.cc/jsnuggets_avatar.jpg', body: "Hey! You are on notice!", >); notification.onclick = function () < window.open("http://carnes.cc"); >; setTimeout(notification.close.bind(notification), 7000); > > notifyMe();
You can play a song like that :
var audio = new Audio('alarm.mp3'); audio.play();
Call the play from the notify() method:
function notify() < var notification = new Notification('TITLE OF NOTIFICATION', < icon: 'http://carnes.cc/jsnuggets_avatar.jpg', body: "Hey! You are on notice!", >); notification.onclick = function () < var audio = new Audio('/pathTo/alarm.mp3'); audio.play(); window.open("http://carnes.cc"); >; setTimeout(notification.close.bind(notification), 7000); >
Java — How do you add music to a JFrame?, Towards the bottom, it has instructions on installing JMF, and then on the next page it shows you how to make basic audio. 1) You need to add the mp3 plug in to play mp3s from the JMF. After adding the plug in .jar file to your project, this is the code you haft to add (I’m doing this from memory, so it may be …
How to play music in java
how to add music to java
BGM = new AudioStream(new FileInputStream("./res/music.wav"));
Java Sound API, Java Sound API. JavaSound is a collection of classes and interfaces for effecting and controlling sound media in java. It consists of two packages. javax.sound.sampled: This package provides an interface for the capture, mixing digital audio. javax.sound.midi: This package provides an interface for MIDI …
Воспроизведение звука в Java
Нормальной русскоязычной информации по теме просто нет. Java-tutorials тоже оставляют желать лучшего. А архитектура javax.sound.sampled хоть и проста, но далеко не тривиальна. Поэтому свой первый пост на Хабре я решил посвятить именно этой теме. Приступим:
Воспроизведение звука
try < File soundFile = new File("snd.wav"); //Звуковой файл //Получаем AudioInputStream //Вот тут могут полететь IOException и UnsupportedAudioFileException AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); //Получаем реализацию интерфейса Clip //Может выкинуть LineUnavailableException Clip clip = AudioSystem.getClip(); //Загружаем наш звуковой поток в Clip //Может выкинуть IOException и LineUnavailableException clip.open(ais); clip.setFramePosition(0); //устанавливаем указатель на старт clip.start(); //Поехали. //Если не запущено других потоков, то стоит подождать, пока клип не закончится //В GUI-приложениях следующие 3 строчки не понадобятся Thread.sleep(clip.getMicrosecondLength()/1000); clip.stop(); //Останавливаем clip.close(); //Закрываем >catch (IOException | UnsupportedAudioFileException | LineUnavailableException exc) < exc.printStackTrace(); >catch (InterruptedException exc) <>
Регулятор громкости
Поигравшись со звуками, вы наверняка захотите иметь возможность программно изменять громкость звука. Java Sound API предоставляет такую возможность с фирменной кривотой.
//Получаем контроллер громкости FloatControl vc = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); //Устанавливаем значение //Оно должно быть в пределах от vc.getMinimum() до vc.getMaximum() vc.setValue(5); //Громче обычного
Этот код нужно поместить между строчками clip.open(ais) и clip.setFramePosition(0).
Упрощаем процесс
import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class Sound implements AutoCloseable < private boolean released = false; private AudioInputStream stream = null; private Clip clip = null; private FloatControl volumeControl = null; private boolean playing = false; public Sound(File f) < try < stream = AudioSystem.getAudioInputStream(f); clip = AudioSystem.getClip(); clip.open(stream); clip.addLineListener(new Listener()); volumeControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); released = true; >catch (IOException | UnsupportedAudioFileException | LineUnavailableException exc) < exc.printStackTrace(); released = false; close(); >> // true если звук успешно загружен, false если произошла ошибка public boolean isReleased() < return released; >// проигрывается ли звук в данный момент public boolean isPlaying() < return playing; >// Запуск /* breakOld определяет поведение, если звук уже играется Если breakOld==true, о звук будет прерван и запущен заново Иначе ничего не произойдёт */ public void play(boolean breakOld) < if (released) < if (breakOld) < clip.stop(); clip.setFramePosition(0); clip.start(); playing = true; >else if (!isPlaying()) < clip.setFramePosition(0); clip.start(); playing = true; >> > // То же самое, что и play(true) public void play() < play(true); >// Останавливает воспроизведение public void stop() < if (playing) < clip.stop(); >> public void close() < if (clip != null) clip.close(); if (stream != null) try < stream.close(); >catch (IOException exc) < exc.printStackTrace(); >> // Установка громкости /* x долже быть в пределах от 0 до 1 (от самого тихого к самому громкому) */ public void setVolume(float x) < if (x<0) x = 0; if (x>1) x = 1; float min = volumeControl.getMinimum(); float max = volumeControl.getMaximum(); volumeControl.setValue((max-min)*x+min); > // Возвращает текущую громкость (число от 0 до 1) public float getVolume() < float v = volumeControl.getValue(); float min = volumeControl.getMinimum(); float max = volumeControl.getMaximum(); return (v-min)/(max-min); >// Дожидается окончания проигрывания звука public void join() < if (!released) return; synchronized(clip) < try < while (playing) clip.wait(); >catch (InterruptedException exc) <> > > // Статический метод, для удобства public static Sound playSound(String path) < File f = new File(path); Sound snd = new Sound(f); snd.play(); return snd; >private class Listener implements LineListener < public void update(LineEvent ev) < if (ev.getType() == LineEvent.Type.STOP) < playing = false; synchronized(clip) < clip.notify(); >> > > >
Пользоваться очень просто, например:
Sound.playSound("sounds/hello.wav").join();
Форматы
Пару слов о поддержке форматов звуковых файлов: забудьте про mp3 и вспомните wav. Также поддерживаются au и aif.