Playing music with java

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Super simple java music player made for fun. A bit annoying to setup however!

cnguy/Simple-Java-Music-Player

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Читайте также:  Mr. Camel

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Simple Java Music player created with Java, Swing, and JMF. I had a lot of fun creating this.

How to setup the playlists for the music player to process and load..

  1. Within the «../model» directory, create a «music» folder, create a folder and name it something easy since you’ll be using it again. In that folder, create playlist subfolders, and place whatever song files you want in there.
    Note: Java doesn’t support MP3s, or at least JMF doesn’t.. so I converted the MP3s to WAVs.).
    In my case, I created two folders: anime_playlist1 & blackbear.
  2. Within the «../controller» directory, create a «playlists» folder. 1. In there, create text files and name them whatever you want. I suggest naming them the same as the folders. Thus, I named them as the following: «anime_playlist1.txt», «blackbear.txt». 2. To register a song to a playlist, go into the appropriate playlist text file, and type on the first line «music/insert_corresponding_folder_name/song_name.wav». If you want to register more songs, just add a new line and repeat it. Because of the way the program is coded, you could type in duplicate addresses to get multiple songs so keep that in mind.
    Examples below!
    anime_openings.txt
music/anime_playlist1/BnHA_op1.wav music/anime_playlist1/G_S2_ed3.wav music/anime_playlist1/G_S2_ed5.wav music/anime_playlist1/G_S2_op2.wav music/anime_playlist1/G_S2_op4.wav 
 music/blackbear/bb_nyla.wav music/blackbear/bb_90210.wav 

Источник

Воспроизведение звука в 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.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

music-player

Here are 536 public repositories matching this topic.

ThatGuyHughesy / music-player

Multi-threaded music player written in Java.

debowin / audiophile

Music Player for the Android Platform

Programie / NetworkMusicPlayer

A network based music player

chomatdam / Streamnshare

[Android] Music player sharing with other devices

cryptomanic / Sensor-Based-Music-Player

rcasanovan / JMusic

Java library to create a mp3 music player

DipankerSingh / Music-Player

Music Player (A Mini JAVA Project )

huhx0015 / AN12_SpotifyStreamer

Android Nanodegree | Project 1-2: Spotify Streamer M: An application that utilizes the Spotify API to allow users to search for and listen to preview clips of popular music artists’ top 10 tracks. Makes full use of the Android Design Support Library to employ a Material Design-compliant appearance.

hiteshsahu / Material-Music-Player-Dashboard

rubelhassan / Gaanwala

A simple android music player

7rajatgupta / BeatBox

Not Beating people up but Beating sounds box in your android !!

Источник

Оцените статью