I'm developing a free alphabet application but I'm not a Java developer. I've made an HTML page where there are about 150 .png
pictures and .mp3
sound file pairs. For example, apple.png
and apple.mp3
would be a pair, and there are going to be more.
I'm using webview to display the webpage with pictures and to know when the user is trying to hear the sound. Here is the code I am currently using:
index.html:
...<a href="mp3/apple.mp3"><img src="apple.png"></a>...
alphabetActivity.java:
...public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".mp3")){
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.parse(url))开发者_StackOverflow;
Toast.makeText(HelloWebviewActivity.this, url, Toast.LENGTH_SHORT).show();
mediaPlayer.start();
} else {
Toast.makeText(HelloWebviewActivity.this, "not mp3", Toast.LENGTH_SHORT).show();
}
return true;
}...
All sounds are stored at assets/www/mp3
.
.
But there is a problem: every time I click on a picture, my application crashes with a Forced close...
message. Is there any way to make it work?
Found my own solution for this problem.
I've copied all the sounds to res/raw folder, changed links in index.html from "mp3/apple.mp3" to "apple" and used this code:
if(mPlayer!=null){
mPlayer.stop();
mPlayer.release();}
int id = getResources().getIdentifier(url.substring(26), "raw", getPackageName());;
mPlayer = MediaPlayer.create(getApplicationContext(), id);
mPlayer.start();
Right now this code is working. Thanks for help =)
As far as I know MediaPlayer.create()
is synchronous.Thus it blocks the UI thred in the place of invocation, creating ANR = Application Not Responsive error. To fix that you need to use asynchronous MediaPlayer.prepareAsync()
calls. For details see:
http://developer.android.com/reference/android/media/MediaPlayer.html
More precisely, instead of:
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(),Uri.parse(url));
you should do something similar to:
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(url));
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
});
Found my own solution for this problem.
I've copied all the sounds to res/raw folder, changed links in index.html from "mp3/apple.mp3" to "apple" and used this code:
if(mPlayer!=null){
mPlayer.stop();
mPlayer.release();}
int id = getResources().getIdentifier(url.substring(26), "raw", getPackageName());;
mPlayer = MediaPlayer.create(getApplicationContext(), id);
mPlayer.start();
Right now this code is working. Thanks for help =)
精彩评论