javafxports如何调用android原生Media Player
作者:互联网
由于javafxports Media尚未实现,我希望使用Android Native MediaPlayer.有谁知道如何做到这一点.
解决方法:
如果您查看GoNative示例here(docs和code),您将找到一种方法将Android本机代码添加到JavaFX项目中.
这是使用Gluon插件将android.media.MediaPlayer添加到JavaFX项目的简单示例.
基于Single View项目,我们首先添加一个包含所需音频方法签名的界面:
public interface NativeAudioService {
void play();
void pause();
void resume();
void stop();
}
现在在我们的View中,我们可以创建按钮来调用这些方法,这些按钮基于实现NativeAudioService接口的AndroidNativeAudio类的实例:
public class BasicView extends View {
private NativeAudioService service;
private boolean pause;
public BasicView(String name) {
super(name);
try {
service = (NativeAudioService) Class.forName("com.gluonhq.nativeaudio.AndroidNativeAudio").newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
System.out.println("Error " + ex);
}
if (service != null) {
final HBox hBox = new HBox(10,
MaterialDesignIcon.PLAY_ARROW.button(e -> service.play()),
MaterialDesignIcon.PAUSE.button(e -> {
if (!pause) {
service.pause();
pause = true;
} else {
service.resume();
pause = false;
}
}),
MaterialDesignIcon.STOP.button(e -> service.stop()));
hBox.setAlignment(Pos.CENTER);
setCenter(new StackPane(hBox));
} else {
setCenter(new StackPane(new Label("Only for Android")));
}
}
@Override
protected void updateAppBar(AppBar appBar) {
appBar.setNavIcon(MaterialDesignIcon.MUSIC_NOTE.button());
appBar.setTitleText("Native Audio");
}
}
现在,我们在Android文件夹下创建本机类.它将使用android API.它会尝试找到我们必须放在/ src / android / assets文件夹下的音频文件audio.mp3:
package com.gluonhq.nativeaudio;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import java.io.IOException;
import javafxports.android.FXActivity;
public class AndroidNativeAudio implements NativeAudioService {
private MediaPlayer mp;
private int currentPosition;
public AndroidNativeAudio() { }
@Override
public void play() {
currentPosition = 0;
try {
if (mp != null) {
stop();
}
mp = new MediaPlayer();
AssetFileDescriptor afd = FXActivity.getInstance().getAssets().openFd("audio.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.setAudioStreamType(AudioManager.STREAM_RING);
mp.setOnCompletionListener(mp -> stop());
mp.prepare();
mp.start();
} catch (IOException e) {
System.out.println("Error playing audio resource " + e);
}
}
@Override
public void stop() {
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
}
@Override
public void pause() {
if (mp != null) {
mp.pause();
currentPosition = mp.getCurrentPosition();
}
}
@Override
public void resume() {
if (mp != null) {
mp.start();
mp.seekTo(currentPosition);
}
}
}
最后,我们可以将项目部署到运行gradlew androidInstall的Android设备上.
标签:android,javafx,android-mediaplayer,javafxports 来源: https://codeday.me/bug/20190918/1810352.html