我将以下代码放在不同的java文件中,
package com.catching.apples;
import java.io.IOException;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.webkit.JavascriptInterface;
public class AudioInterface {
Context mContext;
AudioInterface(Context c) {
mContext = c;
}
private static MediaPlayer mp;
//Play an audio file from the webpage
@JavascriptInterface
public void playAudio(String aud) { //String aud - file name passed
//from the JavaScript function
final MediaPlayer mp;
try {
AssetFileDescriptor fileDescriptor =
mContext.getAssets().openFd(aud);
mp = new MediaPlayer();
mp.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
fileDescriptor.close();
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
我也添加了
mWebView.addJavascriptInterface(new AudioInterface(this), "AndAud");
到我的main_activity.xml
通过我的html代码,我放了AndAud.playAudio(“soundfilename.mp3”);
在播放几次后它会中断。之后又回来了。