如何使用javax.sound.sampled.LineListener?

huangapple go评论73阅读模式
英文:

how to use javax.sound.sampled.LineListener?

问题

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();

        // 打印文件和目录的名称
        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 {
            // 初始化音频系统
            Clip clip = AudioSystem.getClip();

            AudioInputStream AudioInput = AudioSystem.getAudioInputStream(sound);

            // 找到并访问剪辑
            clip.open(AudioInput);

            // 启动剪辑
            clip.start();

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

            clip.drain();
        } catch (Exception e) {
            System.out.println("Error playing music");
        }
    }
}
英文:

I have a program that will ask the user which songs they want to play out of a list of available songs and after the user selects one once the song finishes it asks the user which song they want to play again. I have been told to use line listener for this but I can't seem to figure out how to even after using the oracle docs

my code

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 &lt; pathnames.length; ListNum++) {
System.out.println(ListNum + 1 + &quot;. &quot; + pathnames[ListNum]);
}
for (int playlistLength = 0; playlistLength &lt; pathnames.length; playlistLength++){
if (!songComplete) {
System.out.println(&quot;Which Song would you like to play?&quot;);
int musicChoice = input.nextInt();
musicDir = ProgramMap.userDir + &quot;\\src\\Music\\&quot; + 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(&quot;Now Playing &quot; + FileName);
clip.drain();
}catch (Exception e){
System.out.println(&quot;Error playing music&quot;);
}

}
}

答案1

得分: 2

基本上你需要改变的一件事是将这部分代码替换为:

while (true) {
    System.out.println("你想播放哪首歌?");
    int musicChoice = input.nextInt();
    musicDir = ProgramMap.userDir + "\\src\\Music\\" + pathnames[musicChoice - 1];
    MusicFileChosen = new File(musicDir);
    PlaySound(MusicFileChosen, pathnames[musicChoice - 1]);
}

你可以添加一些逻辑来中断循环。

另外,我建议稍微修改一下 PlaySound 方法:

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("正在播放:" + FileName);
                stream(getAudioInputStream(outFormat, in), line);
                line.drain();
                line.stop();
            }
        }

    } catch (UnsupportedAudioFileException
            | LineUnavailableException
            | IOException e) {
        System.err.println("播放音乐出错\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);
    }
}

它需要播放 MP3,因为你可能会遇到这样的问题:
https://stackoverflow.com/questions/42042533/unknown-frame-size

要向Java Sound添加对MP3的读取支持,将JMF的mp3plugin.jar添加到应用程序的运行时类路径中。
https://www.oracle.com/technetwork/java/javase/download-137625.html

英文:

Basically one thing which you need to change is to replace this:

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

to something like:

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

You can add some logic to break the loop.

Also, I would recommend changing a little bit PlaySound method:

    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(&quot;Now Playing &quot; + FileName);
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
System.err.println(&quot;Error playing music\n&quot; + 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);
}
}

It needs to play MP3 because you can face such a problem:
https://stackoverflow.com/questions/42042533/unknown-frame-size.

To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time classpath of the application. https://www.oracle.com/technetwork/java/javase/download-137625.html

huangapple
  • 本文由 发表于 2020年4月4日 03:41:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61019319.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定