Asset Manager, OpenFd?

后端 未结 2 1151
天涯浪人
天涯浪人 2020-12-21 12:03

I have a file in my assets folder I wish to access, I do so by:

AssetFileDescriptor fileSound = am.openFd(\"myfilepathetc/mymp3.mp3\");

But

相关标签:
2条回答
  • 2020-12-21 12:33

    Why don't you use this instead :

    private void playAudioSound() {
        try {
            AssetFileDescriptor afd = context.getAssets().openFd("sounds/jad0005a.wav");
            MediaPlayer player = new MediaPlayer();
            player.setDataSource(afd.getFileDescriptor());
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-12-21 12:37

    how are you? I know that it is an old question, but I was with the same issue and I found that workaround very useful.

    Java class:

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

    Javascrip file:

    AndAud.playAudio("audio/One.mp3");
    

    On your java WebView:

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

    Ref: http://www.codeproject.com/Tips/677841/Playing-Audio-on-Android-from-an-HTML-File

    0 讨论(0)
提交回复
热议问题