cómo utilizar javax.sound.sampled.LineListener?

warherolion:

Tengo un programa que va a preguntar al usuario qué canciones quieren jugar fuera de una lista de canciones disponibles y después de un usuario selecciona una vez que los acabados de canciones que pregunta al usuario qué canción quieren volver a jugar. Me han dicho que escucha línea de uso para esto, pero me parece que no puede encontrar la manera de incluso después de usar la documentación de Oracle

mi código

public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] pathnames;
File MusicFileChosen;
String musicDir;
boolean songComplete = false;

pathnames = ProgramMap.musicDir.list();

// Print the names of files and directories
for (int ListNum = 0; ListNum < pathnames.length; ListNum++) {
    System.out.println(ListNum + 1 + ". " + pathnames[ListNum]);
}


for (int playlistLength = 0; playlistLength < pathnames.length; playlistLength++){
    if (!songComplete) {
        System.out.println("Which Song would you like to play?");
        int musicChoice = input.nextInt();
        musicDir = ProgramMap.userDir + "\\src\\Music\\" + pathnames[musicChoice - 1];
        MusicFileChosen = new File(musicDir);
        PlaySound(MusicFileChosen, pathnames[musicChoice - 1]);

    }
}
}
public static void PlaySound(File sound, String FileName){
try{
    // Inits the Audio System
    Clip clip = AudioSystem.getClip();

    AudioInputStream AudioInput = AudioSystem.getAudioInputStream(sound);

    //Finds and accesses the clip
    clip.open(AudioInput);

    //Starts the clip
    clip.start();

    System.out.println("Now Playing " + FileName);

    clip.drain();


}catch (Exception e){
    System.out.println("Error playing music");
}

}}

Yan:

Básicamente una cosa que se necesita para el cambio es reemplazar la siguiente:

for (int playlistLength = 0; playlistLength < pathnames.length; playlistLength++){

a algo como:

while (true) {
    System.out.println("Which Song would you like to play?");
    int musicChoice = input.nextInt();
    musicDir = ProgramMap.userDir + "\\src\\Music\\" + pathnames[musicChoice - 1];
    MusicFileChosen = new File(musicDir);
    PlaySound(MusicFileChosen, pathnames[musicChoice - 1]);
}

Se puede añadir un poco de lógica para romper el bucle.

Además, yo recomendaría cambiar un poco pequeña PlaySoundmétodo:

    public static void PlaySound(File sound, String FileName) {
        try (final AudioInputStream in = getAudioInputStream(sound)) {

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

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

                if (line != null) {
                    line.open(outFormat);
                    line.start();
                    System.out.println("Now Playing " + FileName);
                    stream(getAudioInputStream(outFormat, in), line);
                    line.drain();
                    line.stop();
                }
            }

        } catch (UnsupportedAudioFileException
                | LineUnavailableException
                | IOException e) {
            System.err.println("Error playing music\n" + e.getMessage());
        }
    }

    private static 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 static 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);
        }
    }

Se necesita jugar MP3, ya que puede hacer frente a un problema de este tipo: tamaño de la trama desconocida .

Para añadir soporte de lectura MP3 a Java sonido, añadir el mp3plugin.jar del JMF a la ruta de clases de tiempo de ejecución de la aplicación. https://www.oracle.com/technetwork/java/javase/download-137625.html

Supongo que te gusta

Origin http://10.200.1.11:23101/article/api/json?id=404498&siteId=1
Recomendado
Clasificación