0

I put the following code under a diferent java file,

    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();
        }
    }}

I also add

 mWebView.addJavascriptInterface(new AudioInterface(this), "AndAud");

to my main_activity.xml

And through my html code, I put AndAud.playAudio("soundfilename.mp3");

It cuts off after a couple times of it playing. Than comes back on after a bit.

0 Answers0