I play the file like this:

public static void play(String filename) { FileInputStream fis = null; try { fis = new FileInputStream(filename); AudioStream audioStream = new AudioStream(fis); AudioPlayer.player.start(audioStream); } catch (Exception ex) { throw new RuntimeException(ex); } Utils.streamClose(fis); } 

Project test (JUnit 4). If I create a file with main and run it as a Java Application, it plays. If I put it inside the dough, no. The exception does not throw. What is interesting, if you run the test under debugging and take steps, it also plays (and if you just go inside play ()).

What can be wrong?

    2 answers 2

    Most likely, the player launches a separate stream for playback. JUnit sees that the test method has completed and proceeds to the following tests. When all tests are completed, the test environment completes the entire program, along with the player. When you go in steps, the player has time to lose something while you keep running the test method.

    You need to either find in the AudioPlayer API some way to wait for the playback to finish, or insert after calling AudioPlayer.player.start(audioStream); Thread.sleep() to hear something.

    In general, such a test is not a good idea, because In this test, you mainly check the work of someone else's library, and this takes considerable time, and the unit test should be performed as quickly as possible.

    Also, sun.audio is outdated and badly documented, javax.sound or JavaFX is recommended instead.

    • No, I have thought through this option. I waited and ran in a separate thread, but in any case, the test did not end immediately. - Yura Shinkarev
    • And about the wrong idea. Maybe. The situation there is this - I am testing my login. By http I exchange requests, as a result I get a certain url, which I need to open in the browser, log in and I will get back a callback, which I parse, get the required fields and complete the login in the test. And as I do, I open this url in the browser, myself in the test, play the sound (just for me) and wait for the input in the console callback, which I copy from the browser. It looks awful, but I don’t know of any other way - Yura Shinkarev

    Since I only use it in tests on windows, I did it in a simple way:

     public static void playByPowerShell(String filename) throws IOException { String command = String.format("powershell -c (New-Object Media.SoundPlayer '%s').PlaySync();", filename); Runtime.getRuntime().exec(command); }