Javafx - AudioSpectrumListener在根文件外部创建时无法正常工作

时间:2017-09-03 10:10:14

标签: javafx

当我在AudioSpectrumListener对象中创建AudioVisualizer对象时,音乐开始播放后音频自动停止(幅度> -60 dB)。

但是,当我在根应用程序文件中创建AudioSpectrumListener对象时,音频将不会停止,并且updateMagnitude方法的内容会显示。我可以知道如何解决这个问题?

这不起作用:

@Override
public void start(Stage primaryStage) throws IOException{

    AudioVisualizer line = new AudioLine(new File("testing.mp3"));
    primaryStage.setScene(new Scene(line.createContent()));
    primaryStage.show();
    line.play(); //<--Play the audio
}

这是有效的:

private AudioSpectrumListener audioSpectrumListener;

@Override
public void start(Stage primaryStage) throws IOException{

    AudioVisualizer line = new AudioLine(new File("testing.mp3"));

    //Lines below is directly copied from the constructor of AudioVisualizer object
    audioSpectrumListener = (double timestamp, double duration, 
    float[] magnitudes, float[] phases) -> {
        line.updateMagnitude(magnitudes); };
    //-----------------------------------------

    //Lines below is directly copied from the play() method from AudioVisualizer
    line.getAudioMediaPlayer().setAudioSpectrumListener(
    audioSpectrumListener);
    line.getAudioMediaPlayer().play(); 
    //-----------------------------------------

    primaryStage.setScene(new Scene(line.createContent()));
    primaryStage.show();
}

AudioVisualizer

public abstract class AudioVisualizer {
    private MediaPlayer audioMediaPlayer;
    private AudioSpectrumListener audioSpectrumListener;
    private String AUDIO_PATH;

    public AudioVisualizer(File file) {
        AUDIO_PATH = file.toURI().toString();
        audioSpectrumListener = (double timestamp, double duration, float[] magnitudes, float[] phases) -> {
            updateMagnitude(magnitudes);
        };
    }

    public abstract Parent createContent();
    public abstract void updateMagnitude(float[] magnitudes);

    public MediaPlayer getAudioMediaPlayer() {
        if (audioMediaPlayer == null) {
            Media audioMedia = new Media(AUDIO_PATH);
            audioMediaPlayer = new MediaPlayer(audioMedia);
            audioMediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
        }
        return audioMediaPlayer;
    }

    private void startAudio() {
        try {
        //If this line below is commented, the audio will play but the listener will not function
        getAudioMediaPlayer().setAudioSpectrumListener(
            audioSpectrumListener);
        getAudioMediaPlayer().play();
        } catch(Exception e) {System.out.println(e); }
    }

    public void play() {
        this.startAudio();
    }

0 个答案:

没有答案