Audio Player using MediaPlayer class in JMF

孤街浪徒 提交于 2019-12-13 03:38:28

问题


JMF provides a class MediaPlayer which can be used as a full-featured player. However, I can't find a way to play an audio file. Some snippets of the code used.

import javax.media.bean.playerbean.MediaPlayer;

    // ....
    MediaPlayer mp = new MediaPlayer();
    mp.setMediaLocation(location of file);  // <- syntax error!
    mp.start();

But it doesn't work. Eclipse shows this error:

Syntax error on token "setMediaLocation", Identifier expected after this token

..on setMediaLocation() method.

Can someone tell me how to use MediaPlayer class to play audio file? and what is wrong in my coding?


回答1:


You do not literally have ..setMediaLocation(location of file); in the source do you? I thought that was paraphrased.

In that case, the answer is to supply an argument to the setMediaLocation() method. The docs. specify a String or MediaLocator instance.

I avoid using String instances to represent file or URL based sources. If a method needs a File or URL - give it a File or URL. That leaves the best option as a MediaLocator(URL). Here is how it might go. First we need a URL - there are a number of different ways of getting one, depending on what the source of the URL is. E.G. the internet, a file on the local file-system, or an embedded resource in a Jar delivered with the app. The last two might be something like:

File based URL

File mediaFile = new File("user.mp3");
URL mediaURL = mediaFile.toURI().toURL();
// ...

Embedded resource URL

URL mediaURL = this.getClass().getResource("/path/to/our.mp3");
// ...

Once there is a mediaURL instance, we can create a locator and use it in the method.

Using the URL

MediaLocator mediaLocator = new MediaLocator(mediaURL);
MediaPlayer mp = new MediaPlayer();
mp.setMediaLocation(mediaLocator); 
// ...

General tips

  1. JMF is an abandoned API.
  2. Since you seem interested only in audio, look to use Java Sound. It can play audio samples just fine, is part of core Java, and with a small part of the JMF, can play MP3 format (see link for details).
  3. You seem new to the abandoned API being used, Eclipse and debugging. Perhaps you should focus on simpler things for the moment. Media handling is an advanced topic.


来源:https://stackoverflow.com/questions/11133456/audio-player-using-mediaplayer-class-in-jmf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!