Comment puis-je jouer du son en Java?


Je veux pouvoir lire des fichiers audio dans mon programme. Où dois-je chercher?

Author: pek, 2008-08-25

9 answers

J'ai écrit le code suivant qui fonctionne bien. Mais je pense que cela ne fonctionne qu'avec le format .wav.

public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {
  // The wrapper thread is unnecessary, unless it blocks on the
  // Clip finishing; see comments.
    public void run() {
      try {
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(
          Main.class.getResourceAsStream("/path/to/sounds/" + url));
        clip.open(inputStream);
        clip.start(); 
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }
  }).start();
}
 117
Author: pek, 2016-06-08 05:54:48

La piste sonore du tutoriel Java vaut la peine d'être le point de départ.

 23
Author: yanchenko, 2012-04-01 17:10:58

Un mauvais exemple:

import  sun.audio.*;    //import the sun.audio package
import  java.io.*;

//** add this into your application code as appropriate
// Open an input stream  to the audio file.
InputStream in = new FileInputStream(Filename);

// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);         

// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);            

// Similarly, to stop the audio.
AudioPlayer.player.stop(as); 
 21
Author: Greg Hurlman, 2011-09-27 00:22:22

Je ne voulais pas avoir autant de lignes de code juste pour jouer un simple son. Cela peut fonctionner si vous avez le paquet JavaFX (déjà inclus dans mon jdk 8).

private static void playSound(String sound){
    // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
    URL file = cl.getResource(sound);
    final Media media = new Media(file.toString());
    final MediaPlayer mediaPlayer = new MediaPlayer(media);
    mediaPlayer.play();
}

Remarque : Vous devez initialiser JavaFX . Un moyen rapide de le faire est d'appeler le constructeur de JFXPanel () une fois dans votre application:

static{
    JFXPanel fxPanel = new JFXPanel();
}
 8
Author: Cyril Duchon-Doris, 2017-05-23 11:54:51

Pour lire le son en java, vous pouvez vous référer au code suivant.

import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;

// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {

   public SoundClipTest() {
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setTitle("Test Sound Clip");
      this.setSize(300, 200);
      this.setVisible(true);

      try {
         // Open an audio input stream.
         URL url = this.getClass().getClassLoader().getResource("gameover.wav");
         AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
         // Get a sound clip resource.
         Clip clip = AudioSystem.getClip();
         // Open audio clip and load samples from the audio input stream.
         clip.open(audioIn);
         clip.start();
      } catch (UnsupportedAudioFileException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (LineUnavailableException e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {
      new SoundClipTest();
   }
}
 7
Author: Ishwor, 2015-05-29 20:04:16

Pour une raison quelconque, la réponse supérieure de wchargin me donnait une erreur de pointeur null lorsque j'appelais ceci.getClass().getResourceAsStream ().

Ce qui a fonctionné pour moi était le suivant:

void playSound(String soundFile) {
    File f = new File("./" + soundFile);
    audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());  
    Clip clip = AudioSystem.getClip();
    clip.open(audioIn);
    clip.start();
}

Et je jouerais le son avec:

 playSound("sounds/effects/sheep1.wav");

Sons/effets/moutons 1.wav est situé dans le répertoire de base de mon projet dans Eclipse (donc pas dans le dossier src).

 4
Author: Andrew Jenkins, 2016-06-08 04:41:08

Il existe une alternative à l'importation des fichiers audio qui fonctionne à la fois dans les applets et les applications: convertissez les fichiers audio en .fichiers java et utilisez-les simplement dans votre code.

, j'ai développé un outil qui rend ce processus beaucoup plus facile. Cela simplifie un peu l'API Java Sound.

Http://stephengware.com/projects/soundtoclass/

 4
Author: Stephen Ware, 2016-08-01 20:50:01

J'ai créé un framework de jeu il y a quelque temps pour fonctionner sur Android et Desktop, la partie de bureau qui gère le son peut peut-être être utilisée comme source d'inspiration pour ce dont vous avez besoin.

Https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java

Voici le code de référence.

package com.athanazio.jaga.desktop.sound;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

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

public class Sound {

    AudioInputStream in;

    AudioFormat decodedFormat;

    AudioInputStream din;

    AudioFormat baseFormat;

    SourceDataLine line;

    private boolean loop;

    private BufferedInputStream stream;

    // private ByteArrayInputStream stream;

    /**
     * recreate the stream
     * 
     */
    public void reset() {
        try {
            stream.reset();
            in = AudioSystem.getAudioInputStream(stream);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);
            line = getLine(decodedFormat);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            line.close();
            din.close();
            in.close();
        } catch (IOException e) {
        }
    }

    Sound(String filename, boolean loop) {
        this(filename);
        this.loop = loop;
    }

    Sound(String filename) {
        this.loop = false;
        try {
            InputStream raw = Object.class.getResourceAsStream(filename);
            stream = new BufferedInputStream(raw);

            // ByteArrayOutputStream out = new ByteArrayOutputStream();
            // byte[] buffer = new byte[1024];
            // int read = raw.read(buffer);
            // while( read > 0 ) {
            // out.write(buffer, 0, read);
            // read = raw.read(buffer);
            // }
            // stream = new ByteArrayInputStream(out.toByteArray());

            in = AudioSystem.getAudioInputStream(stream);
            din = null;

            if (in != null) {
                baseFormat = in.getFormat();

                decodedFormat = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED, baseFormat
                                .getSampleRate(), 16, baseFormat.getChannels(),
                        baseFormat.getChannels() * 2, baseFormat
                                .getSampleRate(), false);

                din = AudioSystem.getAudioInputStream(decodedFormat, in);
                line = getLine(decodedFormat);
            }
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    private SourceDataLine getLine(AudioFormat audioFormat)
            throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);
        return res;
    }

    public void play() {

        try {
            boolean firstTime = true;
            while (firstTime || loop) {

                firstTime = false;
                byte[] data = new byte[4096];

                if (line != null) {

                    line.start();
                    int nBytesRead = 0;

                    while (nBytesRead != -1) {
                        nBytesRead = din.read(data, 0, data.length);
                        if (nBytesRead != -1)
                            line.write(data, 0, nBytesRead);
                    }

                    line.drain();
                    line.stop();
                    line.close();

                    reset();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 3
Author: hamilton.lima, 2013-03-29 01:01:01

Ce fil est plutôt vieux mais j'ai déterminé une option qui pourrait s'avérer utile.

Au lieu d'utiliser la bibliothèque Java AudioStream, vous pouvez utiliser un programme externe comme Windows Media Player ou VLC et l'exécuter avec une commande de console via Java.

String command = "\"C:/Program Files (x86)/Windows Media Player/wmplayer.exe\" \"C:/song.mp3\"";
try {
    Process p = Runtime.getRuntime().exec(command);
catch (IOException e) {
    e.printStackTrace();
}

Cela créera également un processus distinct qui peut être contrôlé par le programme.

p.destroy();

Bien sûr, cela prendra plus de temps à exécuter que d'utiliser une bibliothèque interne, mais il peut y avoir des programmes qui peuvent démarrer plus rapidement et peut-être sans interface graphique compte tenu de certaines commandes de la console.

Si le temps n'est pas essentiel, cela est utile.

 -1
Author: Galen Nare, 2016-10-10 19:38:26