我写了一个扩展Android mediaplayer的类,类如下
package it.ccevas.ccevasandroid;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
public class MyMediaPlayer extends MediaPlayer {
public MyMediaPlayer(){
super();
setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
start();
}
});
setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (what == -38){
return true;
}
return false;
}
});
}
public boolean changeSource (String urlfile){
try{
reset();
setAudioStreamType(AudioManager.STREAM_MUSIC);
setDataSource(urlfile);
prepare();
seekTo(0);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
start();
return true;
}
}
它在 Android 4.x 上运行良好
但在 Android 2.x 上,它仅适用于存储在 SD 上的文件,不适用于远程文件,例如“ http://www.something.com/myfile.mp3 ”
清单上的权限是正确的:
<uses-permission android:name="android.permission.INTERNET"/>
这是log.cat
:
05-03 10:15:06.699: E/MediaPlayer(414): Attempt to call getDuration without a valid mediaplayer
05-03 10:15:06.699: E/MediaPlayer(414): error (-38, 0)
05-03 10:15:06.699: E/MediaPlayer(414): error (1, -2147483648)
05-03 10:15:06.789: E/MediaPlayer(414): Error (-38,0)
05-03 10:15:57.991: E/MediaPlayer(414): Error (1,-2147483648)