Java audio 🔊
Vložit
- čas přidán 7. 09. 2024
- Java audio sound music player tutorial explained
#java #audio #sound #music
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.*;
public class Main {
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException{
Scanner scanner = new Scanner(System.in);
File file = new File("Level_Up.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
String response = "";
while(!response.equals("Q")) {
System.out.println("P = play, S = Stop, R = Reset, Q = Quit");
System.out.print("Enter your choice: ");
response = scanner.next();
response = response.toUpperCase();
switch(response) {
case ("P"): clip.start();
break;
case ("S"): clip.stop();
break;
case ("R"): clip.setMicrosecondPosition(0);
break;
case ("Q"): clip.close();
break;
default: System.out.println("Not a valid response");
}
}
System.out.println("Byeeee!");
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.*;
public class Main {
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException{
Scanner scanner = new Scanner(System.in);
File file = new File("Level_Up.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
String response = "";
while(!response.equals("Q")) {
System.out.println("P = play, S = Stop, R = Reset, Q = Quit");
System.out.print("Enter your choice: ");
response = scanner.next();
response = response.toUpperCase();
switch(response) {
case ("P"): clip.start();
break;
case ("S"): clip.stop();
break;
case ("R"): clip.setMicrosecondPosition(0);
break;
case ("Q"): clip.close();
break;
default: System.out.println("Not a valid response");
}
}
System.out.println("Byeeee!");
}
}
When you realize you didn't have to watch the whole video. Still helpful tho. THXXXXXXXXX
Bro how are you so smart? How do you know these things? Just how???
@@Code_Machine read the documentation? or watch youtube tutorial if u are lazy like me 🤣
i had a question an i instanciate an object based on another objects properties such as
if I had created hair and a getter
Color color = hair.getColor();
@@cayman_islands Your file must be .wav extension not mp3.
This is the first time I have ever played audio through programming. The joy it gave me was very immense. Thank you very much for putting out this tutorial.
True... Same with me
you are the only one who made me understand how to put music in java
awesome!
Quick tip for y'all. Java can't handle common high quality files (48000.0 Hz, 32 bit, etc), if you encounter something like this: line with format PCM_FLOAT 48000.0 Hz, 32 bit, stereo, 8 bytes/frame not supported. You'll have to downgrade your file, using the web converter and tuning it to ~20000 does the trick ;D
Thx buddy
I made it 16000 Hz 8 bits and it still won’t work
@@Noman23444 odd, We will have to read some docs to know what after the limitations exactly then
Even 2 years later, I love you
Ok thanks bro
Thank you for the simple and clear explanation! I really want to go deeper into this topic, and have done a bit of research on Java's Line Mixer and stuff. I am a musician and audio engineer and I want to start building some music creation tools, or mp3 player type projects for my portfolio.
Maby I use this for adding jumpscares to programms that have nothing to do with horror... XD
YES! That would be great 😂
@@BroCodez could not get audio input stream from input file , that what exception says
@@BroCodez in my intellij its not working
NO WAY THIS WAS EXACTLY WHAT I NEEDED OMG YOU ARE THE BEST
I think you might have given me the idea to create this video lol
@@BroCodez 😂
@@BroCodez you are the best bro! Could you maybe make a video on CardLayout class too?
Bro I have some questions:
1- How can we play a sound that will automaticly loop when it ends until we stop it with clip.stop() ?
2- How can we set the volume of the sound?
3- Can we set different volumes to different sounds while playing all of them at once? For example we have some sound effects and music in some app and we want to play music at %70 volume and sound effects at %50 volume. (We want to play them at the same time, the music will be playing in the background and when we play the sound effect, the music will not stop)
1. clip.loop(clip.LOOP_CONTINUOUSLY);
2 + 3. You can set the individual sound levels for each clip using this set of code. I would recommend placing this code in a method to call when you need it:
FloatControl volume = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
// set the percent (between 0.0 and 1.0)
double percent = 0.5;
float dB = (float) (Math.log(percent) / Math.log(10.0) * 20.0);
volume.setValue(dB);
@@BroCodez thank you so much bro you are the best!
No words can express this feeling.
I think the simplest way to suspend your program is just "while(boolean var) { }" or in this case "while(clip.isRunning()) { }". Both of these will trap the thread and allow music to continue playing until the expression resolves to false.
I love this channel. I am very much thankful to bro code for coding content. I teach everyday new new thing.
Thank you
Bro code❤❤❤
I actually preferred using if statements for this one because i used p for both play and pause. i also made a fast forward and a rewind system :)
File file = new File("src/sound.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
System.out.println("P = play/pause, R = reset, RR = rewind 5s, FF = fast forward 5s, Q = quit");
String response = scanner.next();
response = response.toLowerCase();
boolean isPlaying = false;
while(!response.equals("q")) {
System.out.println("P = play/pause, R = reset, RR = rewind 5s, FF = fast forward 5s, Q = quit");
if(response.equals("p")) {
if(!isPlaying) {
clip.start();
isPlaying = true;
} else {
clip.stop();
isPlaying = false;
}
} else if (response.equals("r")) {
clip.setMicrosecondPosition(0);
} else if (response.equals("rr")) {
clip.setMicrosecondPosition(clip.getMicrosecondPosition() - 5000000);
// NOTE: 1000000 is 1 second
} else if (response.equals("ff")) {
clip.setMicrosecondPosition(clip.getMicrosecondPosition() + 5000000);
} else {
System.out.println("invalid input");
}
response = scanner.next().toLowerCase();
}
kinda confusing
great video, appreciate the hard works you've done
when watching your vids I constantly see ads from the university I tried to get into but failed... Bro it's kinda depressing but won't stop me from learning from your supersupersuper tutorials ;DDD
You can get into programming without a programming degree! Just keep your effort as close to 100% as possible and never worry that you might fail, because it's toxic to worry about things that are out of your control. What you have is each day! Lose yourself to the music
@@Simis999 thank you :) Finally, I did it. I'm on my dream course of study but you're absolutely right - it's all about hard work and doing your best every single day
Wao man, it's what i was looking for ... 3 months ago, I don't know why I didn't find this amazing video
Thxxxxxxxxx mannnnnn you're the best
Love from India 🇮🇳🇮🇳🇮🇳🇮🇳🇮🇳
THAN YOU VERY MUCH BRO!!!!!! I CAN NOW MAKE MY CODE PLAY THE BIRD
Thanks Bro, after watching your videos i get more motivation to code
Thank you bro, with 3:25 you saved me
Hi, i'm a beginner with java and I followed your snake game tutorial as well, and wanted to add a sound effect when an apple is eaten. For some reason I can't get it to work. Here is my code:
public void playSound() throws LineUnavailableException, IOException, UnsupportedAudioFileException {
File file = new File("appleeaten.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
}
public void checkApple() {
if((x[0] == appleX) && (y[0]) == appleY) {
bodyParts++;
applesEaten++;
try {
playSound();
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
e.printStackTrace();
}
newApple();
}
}
there are no errors in the code but no sound actually plays when I test it. Do you know what I did wrong?
Best of all... no ads 😎🎧
Oh, there's ads lol
I try not to place too many in because I know it gets annoying
@Bro Code no I mean no ads when you listen to music in eclipse 🤣
@Bro Code can you teach us how to make a playlist? 😂
Thank you so much! I'm also using Eclipse so some other videos on this topic that I watched didn't help.
Great video! What keyboard are you using? It sounds satisfying :)
Yu're a f*cking g, i've been searching for this for like two years
I have a exception please help me:
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1189)
at playmusic.Main.main(Main.java:15)
C:\Users\ferid\AppData\Local\NetBeans\Cache\8.2\executor-snippets
un.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
Bro, you are the best...
Thanks for making such free videos
I just subscribed after the second video from If statement to Audio. Itbreallybmakes sense when they say, if you really know the base of Java, everything else will follow easily.
Thanks a lot.i am going for SDET,so Java is the main programming language as the backbone... thanks
Thanks for helping Dude. You have explained it so nicely
Exception in thread "main" javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 32000.0 Hz, 24 bit, mono, 3 bytes/frame, *little-endian not supported*
What does this mean?
Exception in thread "main" java.io.FileNotFoundException: nocturnal.wav (The system cannot find the file specified)
I like your Taste in music
i know right some interesting music
It's a real banger
@@BroCodez where do I find it tho
Hi Bro! I am back, hope you remember me :D just a little tip here, when you teach us Java in Eclipse, press ctrl + m. It will make it full screen and we would be able to see the code properly. I would certainly like it :D
ha! of course I remember you Moonlight!
Sweet, didn't know about that crtl + m trick! I'll have to try it
@@BroCodez awesome! :D
or don't use eclipse and use intelliJ instead
Best coding channel!
dude thats the coolest tutorial so far, well im new to your channel so
the filepath is not found.... can't understand i put the correct String..
Never heard of that. Good to know. Thanks
2k likes out of 59k views....shame. Can we stop for a minute and think that this dude shares his time and knowledge for free... :/
It's not free, you give from your soul.
Thank you for such a wonderful video.
Is there a way to put this on my UI? and btw you always do a good job. Good thing I listened to my friends because they introduced me to your channel
helped me out alot man thanks
thanks for watching epic
every video this guy makes deserves a like
Finally I can listen to epic sax guy in my java application.
Hey, bro!!
I've got a question:
I've been trying to make a JButton that when clicked will produce an audio. I created 3 classes. Within the LaunchAudio Class, in the ActionPerformed method, I created an instance of the class audio where wrote the audio code. I tried to make the button static and make a while loop that says e.getSource() == button, clip.start(); and a sysout. But it doesn't work. There are no errors in the code. But there is no sound when I click the button. the print lines are there tho. May you help me out with this?
And thx for all your videos BRO!!!! Real HERO!
really thankful for this tutorial
Thank you from Egypt
good video to practice multiple concept, Ty
Ah, thank you! after series of check on stack overflow. finally worked! voila
I stucked pretty fast at the first import, netbeans says "import javax.sound.sampled.*; not visible. Package javax.sound.sampled is declared in module java.desktop, but module "my main class" does not read it.
Has anyone got similar error?
How would you make a program that plays a variable pitch tone? I want to change the sound's pitch based on the distance between two points on the screen
Am very glad. i was finally able to complet it after my second attempt. thank you very much.
but i want to ask, is it possible to add more sounds and to delete sound aswell?
You are so underrated dude
Thank you very much
Useful. But most of the video is about generic command line processing not so much about audio.
Hey, thanks for the great tutorial! I have a question, after calling the sound method I created, my program stops executing the following proceeding lines. For example, I want to play a sound when I run my start game function, then have the game logic still be executed, but where ever I call the sound, my game just comes to a complete halt, how do I fix this?
why don't put try putting it inside of the constructor?
Friendly reminder to everyone: The file shouldn't contain spaces or it won't work
I didn't understand the first part of the code:
File file = new File("Level_Up.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
Thanks Bro for keeping it simple 😊
Bhai exception aa raha hai.
Thanks, Bro! ☕ You're awesome!
I am confused. How do I install the package?! I can't find any instructions on how to install it!
How can i add on this and make it open multiple files and be able to play lot more songs and some other features too
You are the best bro!❤
Thank you so much
Thank bro for video
gorgeous!
Nice video, But why the File work only with wav Script?
What about the others?
Very nice
Great video Broo THANKS🤘🏿....Are you still going to do more videos on audio? How do eye have more than one song? and how to create a desktop of my mp3 player?
maybe, it depends on the demand
Great
Hi Bro! Like im making a game and want to have a background music, that once the music stops, the next music in an array starts. But like you said bout the gui or Scanner bit, so when youre Playing a game you'd have to pause the game, click ok or scanner to continue, is there any other way.
Thank You very much Sirrrrr😍
heloo brozz check previous videos of bro code to learn more about java🔥🔥
Iam not his frnd ... and i love this channel because of. he is not the like other youtubers . those who are making a simple program more complicated. But in this channel learning java makes easy for me
I think i wasted my time on other tutorial channel..
Bro🔥🔥🔥
😍😍😍😍😍
bro is the best bro from all my bros and I haven't even met bro
why do i have an error on javax.sound.sample.*; it says the package is not accessible
This is the music tape from " The Forest", am I right? Sure this sounds familiar 🙄🙄🙄
But i think this time round am going to be expert in programming with code bro
Thank you for share your knowledge!!!!!! Leon T S Ferreira
System.out.println("You are a Genius");
niceeeeee
super awesome
I got Exception in thread "main" javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 48000.0 Hz, 24 bit, mono, 3 bytes/frame, little-endian not supported. how to fix?
Excellent! But how about mp3 ?
you have to convert it, java doesn't read mp3
Thank you so much sir.
Can you tell how to increase and decrease the volume?
Hello, Bro! I can already code in Javascript an I am currently learning Java. One thing that is still confusing me is this:
AudioInputStream audioStream = AudioSystem.getInputStream(file);
why do I have to write AudioInputStream before the name of the object/variable I am creating? what is stored in the audioStream variable is the returned value from the AudioSystem static method "getInputStream" right?
in javascript the syntax would look something like this
const audioStream = audioSystem.getInputStream() (if the method audioSystem.getInputStream actually existed in javascript)
did you figure this out?? I am having the same doubt.
@@it04ameekanazreen59 hello and yes haah
@@it04ameekanazreen59 in Java, its mandatory to define the tipe of the variable. boolean, int. String. But not only that, every instanxe of a class, be it custom or predefined, should also have its type stated before the name of the variable
So if I created a class called GameClass
Class GameClass{
public string gameString(){
return "youre playing a game",}
public AnotherRandomClass createAnInstanceOfThatRandomClass (){
return new AnotgerRandomClass();
}
}
I would have to do the following
GameClass gameClassObj = new GameClass()
in my eclipse dont find the file whyy ??
i had followed all the passage
Very good video! But I have still one question: How can I automatically execute code after the audio finished playing?
You could add it before breaking out of a switch case, or after the while loop is done (where he prints 'bye'), etc.
huge thank you!
thank you very good vid!
Great! Thank you Bro!
why am i getting this exception ? Exception in thread "main" java.lang.Error: Unresolved compilation problem:
AudioSystem.getAudioInputStream cannot be resolved to a type
at sound.sound.main(sound.java:17)
im having this same issue
lets go!
anybody got: "The package javax.sound.sampled is not accessible" ??
I have no errors but i has no sound at all, did I miss some eclipse configuration? My machine is linux
Thanks
8:03
Amazing, thanks
Anyone else getting this error?
Exception in thread "main" java.lang.UnsatisfiedLinkError: no icedtea-sound in java.library.path
can i automtically start the sound when i run the class? without having any input?
Thanks bro
piece of cake broh!