首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用麦克风输入作为JavaFX媒体播放器的输入?

如何使用麦克风输入作为JavaFX媒体播放器的输入?
EN

Stack Overflow用户
提问于 2019-01-03 19:16:01
回答 1查看 548关注 0票数 2

我想使用JavaFX媒体播放器实时播放麦克风输入(以分析其频率)。问题是,MediaPlayer只接受字符串作为源。我知道如何将麦克风输入写入字节数组和文件中。

使用字节数组作为MediaPlayer的源(对我来说)是不可能的。我尝试使用临时文件,但这导致了以下错误:

代码语言:javascript
复制
Exception in thread "JavaFX Application Thread" MediaException: MEDIA_UNSUPPORTED : Empty signature!

我想这是因为我正在使用一个文件作为输入,同时我还在向其中写入新数据。我到现在为止的完整代码:

代码语言:javascript
复制
public class Music {

static AudioFormat format;
static DataLine.Info info;

public static void input(int i, int j, int pinState) {
    format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false);

    try {
        info = new DataLine.Info(TargetDataLine.class, format);
        final TargetDataLine targetLine = (TargetDataLine) AudioSystem.getLine(info);
        targetLine.open();

        AudioInputStream audioStream = new AudioInputStream(targetLine);

        File temp = File.createTempFile("Input", ".wav");
        temp.deleteOnExit();

        Thread targetThread = new Thread() {
            public void run() {
                targetLine.start();
                try {
                    AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, temp);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        targetThread.start();

        Media media = new Media(temp.toURI().toURL().toString());
        MediaPlayer player = new MediaPlayer(media);
        player.setAudioSpectrumThreshold(-100);
        player.setMute(false);
        player.setAudioSpectrumListener(new AudioSpectrumListener() {
             @Override  
             public void spectrumDataUpdate(double timestamp, double duration, float[] magnitudes, float[] phases) {
                 if(Var.nodeController[i] == 3) { //testing if the targetLine should keep on capturing sound
                 } else {
                     targetLine.stop();
                     targetLine.close();
                     player.stop();
                 }
             }
        });
        player.play();
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}    

}

我需要找到一种解决方案来使用麦克风输入作为MediaPlayer输入,可以使用文件或字节数组,也可以使用任何其他可能的解决方案。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54021239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档