program tip

자바에서 .mp3 및 .wav를 재생 하시겠습니까?

radiobox 2020. 8. 13. 08:13
반응형

자바에서 .mp3 및 .wav를 재생 하시겠습니까?


Java 애플리케이션에서 .mp3.wav파일을 어떻게 재생할 수 있습니까? 스윙을 사용하고 있습니다. 이 예와 같은 것을 인터넷에서 찾아 보았습니다.

public void playSound() {
    try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.start();
    } catch(Exception ex) {
        System.out.println("Error with playing sound.");
        ex.printStackTrace();
    }
}

그러나 이것은 .wav파일 만 재생 합니다.

다음과 동일 :

http://www.javaworld.com/javaworld/javatips/jw-javatip24.html

같은 방법으로 .mp3파일과 .wav파일을 모두 재생할 수 있기를 바랍니다 .


자바 FX는이 MediaMediaPlayermp3 파일을 재생합니다 클래스.

예제 코드 :

String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();

다음 import 문이 필요합니다.

import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

순수한 자바 mp3 플레이어 인 mp3transform을 작성했습니다 .


.wav는 Java API로만 재생할 수 있습니다.

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

암호:

AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();

그리고 jLayer로 .mp3 재생


사용한 지 오래 되었지만 JavaLayer 는 MP3 재생에 적합합니다.


BasicPlayerAPI를 사용하는 것이 좋습니다. 오픈 소스이고 매우 간단하며 JavaFX가 필요하지 않습니다. http://www.javazoom.net/jlgui/api.html

zip 파일을 다운로드하고 추출한 후 다음 jar 파일을 프로젝트의 빌드 경로에 추가해야합니다.

  • basicplayer3.0.jar
  • lib 디렉토리 모든 jar (BasicPlayer3.0 내부)

다음은 최소한의 사용 예입니다.

String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
    player.open(new URL("file:///" + pathToMp3));
    player.play();
} catch (BasicPlayerException | MalformedURLException e) {
    e.printStackTrace();
}

필수 수입품 :

import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

그게 음악 재생을 시작하는 데 필요한 전부입니다. 플레이어는 자신의 재생 스레드를 시작하고 관리하며 재생, 일시 중지, 다시 시작, 중지검색 기능을 제공합니다.

좀 더 고급 사용법은 jlGui Music Player를 참조하십시오. 오픈 소스 WinAmp 클론 : http://www.javazoom.net/jlgui/jlgui.html

가장 먼저 살펴볼 클래스는 PlayerUI (javazoom.jlgui.player.amp 패키지 내부)입니다. BasicPlayer의 고급 기능을 꽤 잘 보여줍니다.


표준 javax.sound API, 단일 Maven 종속성, 완전한 오픈 소스 사용 ( Java 7 필요) :

pom.xml

 <!-- 
    We have to explicitly instruct Maven to use tritonus-share 0.3.7-2 
    and NOT 0.3.7-1, otherwise vorbisspi won't work.
   -->
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>tritonus-share</artifactId>
  <version>0.3.7-2</version>
</dependency>
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>mp3spi</artifactId>
  <version>1.9.5-1</version>
</dependency>
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>vorbisspi</artifactId>
  <version>1.0.3-1</version>
</dependency>

암호

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;

public class AudioFilePlayer {

    public static void main(String[] args) {
        final AudioFilePlayer player = new AudioFilePlayer ();
        player.play("something.mp3");
        player.play("something.ogg");
    }

    public void play(String filePath) {
        final File file = new File(filePath);

        try (final AudioInputStream in = getAudioInputStream(file)) {

            final AudioFormat outFormat = getOutFormat(in.getFormat());
            final Info info = new Info(SourceDataLine.class, outFormat);

            try (final SourceDataLine line =
                     (SourceDataLine) AudioSystem.getLine(info)) {

                if (line != null) {
                    line.open(outFormat);
                    line.start();
                    stream(getAudioInputStream(outFormat, in), line);
                    line.drain();
                    line.stop();
                }
            }

        } catch (UnsupportedAudioFileException 
               | LineUnavailableException 
               | IOException e) {
            throw new IllegalStateException(e);
        }
    }

    private AudioFormat getOutFormat(AudioFormat inFormat) {
        final int ch = inFormat.getChannels();

        final float rate = inFormat.getSampleRate();
        return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
    }

    private void stream(AudioInputStream in, SourceDataLine line) 
        throws IOException {
        final byte[] buffer = new byte[4096];
        for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
            line.write(buffer, 0, n);
        }
    }
}

참조 :


The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

Here is the code for the class

public class SimplePlayer {

    public SimplePlayer(){

        try{

             FileInputStream fis = new FileInputStream("File location.");
             Player playMP3 = new Player(fis);

             playMP3.play();

        }  catch(Exception e){
             System.out.println(e);
           }
    } 
}

and here are the imports

import javazoom.jl.player.*;
import java.io.FileInputStream;

To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.

Features:

  • very low CPU usage (~2%)
  • incredible small library (~90KB)
  • doesn't need JMF (Java Media Framework)
  • easy to integrate in any application
  • easy to integrate in any web page (as applet).

For a complete list of its methods and attributes you can check its documentation here.

Sample code:

import jaco.mp3.player.MP3Player;
import java.io.File;

public class Example1 {
  public static void main(String[] args) {
    new MP3Player(new File("test.mp3")).play();
  }
}

For more details, I created a simple tutorial here that includes a downloadable sourcecode.


You need to install JMF first (download using this link)

File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();

don't forget to add JMF jar files


Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.

You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.


Using MP3 Decoder/player/converter Maven Dependency.

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class PlayAudio{

public static void main(String[] args) throws FileNotFoundException {

    try {
        FileInputStream fileInputStream = new FileInputStream("mp.mp3");
        Player player = new Player((fileInputStream));
        player.play();
        System.out.println("Song is playing");
        while(true){
            System.out.println(player.getPosition());
        }
    }catch (Exception e){
        System.out.println(e);
    }

  }

}

To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.

Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.


Use this library: import sun.audio.*;

public void Sound(String Path){
    try{
        InputStream in = new FileInputStream(new File(Path));
        AudioStream audios = new AudioStream(in);
        AudioPlayer.player.start(audios);
    }
    catch(Exception e){}
}

참고URL : https://stackoverflow.com/questions/6045384/playing-mp3-and-wav-in-java

반응형