简体   繁体   中英

Javafx can't play mp3 file with MediaException on ubuntu 20

  1. configuration: ubuntu 20, javafx 11, jdk15, language level 8
  2. problem: mp3 file could be directly play on ubuntu, while can't be played in following code, but the code can be used to play *.wav and *.aiff audio files, except mp3:
    Media media = new Media(new File("assets/audios/shoot.mp3").toURI().toString());
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.play();
  1. exception:
    Exception in thread "main" MediaException: UNKNOWN : com.sun.media.jfxmedia.MediaException: Could not create player! : com.sun.media.jfxmedia.MediaException: Could not create player!
    at javafx.scene.media.MediaException.exceptionToMediaException(MediaException.java:146)
    at javafx.scene.media.MediaPlayer.init(MediaPlayer.java:518)
    at javafx.scene.media.MediaPlayer.<init>(MediaPlayer.java:421)
    at com.aldora.tankwar.Tools.playSound(Tools.java:18)
    at com.aldora.tankwar.App.main(App.java:146)
Caused by: com.sun.media.jfxmedia.MediaException: Could not create player!
    at com.sun.media.jfxmediaimpl.NativeMediaManager.getPlayer(NativeMediaManager.java:295)
    at com.sun.media.jfxmedia.MediaManager.getPlayer(MediaManager.java:118)
    at javafx.scene.media.MediaPlayer.init(MediaPlayer.java:474)
  1. debug result: com.sun.media.jfxmediaimpl.platform.gstreamer.GSTPlatform.createMediaPlayer throws media error: ERROR_MEDIA_NULL

After some trial and error, I found this can't be walked around by upgrading javafx, switching from javafx11 to javafx16 can solve it. javafx download link

The problem is in java's "sound.properties" config file. I'm now on Ubuntu 20.04, with java-11-openjdk, so, edited /etc/java-11-openjdk/sound.properties and added the following lines at the end:

javax.sound.sampled.Clip=com.sun.media.sound.DirectAudioDeviceProvider
javax.sound.sampled.Port=com.sun.media.sound.PortMixerProvider
javax.sound.sampled.SourceDataLine=com.sun.media.sound.DirectAudioDeviceProvider
javax.sound.sampled.TargetDataLine=com.sun.media.sound.DirectAudioDeviceProvider

For deep in, read: https://keithp.com/blogs/Java-Sound-on-Linux/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM