我要玩android中的MP3文件,但我得到這個錯誤:錯誤的播放文件:NullPointerException異常Android中
java.lang.NullPointerException at HelloAndroid.playMusic
我的代碼如下
package com.bestvalue.hello;
/*import android.util.Log;*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.net.Uri;
public class HelloAndroid extends Activity {
public static final String DebugTag = "LogInfo";
public MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("keke napep");
playMusic();
setContentView(tv);
Log.i(DebugTag, "Info about my app na");
}
public void playMusic() {
try {
Uri fileName = Uri.parse("http://www.perlgurl.org/podcast/archives/podcasts/PerlgurlPromo.mp3");
mp= MediaPlayer.create(this, fileName);
mp.start();
} catch (Exception e){
Log.e(DebugTag, "Error Playing File", e);
}
}
@Override
protected void onStop() {
if (mp != null) {
mp.stop();
mp.release();
}
super.onStop();
}
}
將我做些什麼來解決這個錯誤?
感謝
UPDATE
package com.bestvalue.hello;
/*import android.util.Log;*/
import android.app.Activity;
//import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.media.AudioManager;
import android.media.MediaPlayer;
public class HelloAndroid extends Activity {
public static final String DebugTag = "LogInfo";
private MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("keke napep");
playMusic();
setContentView(tv);
}
public void playMusic() {
try {
String url = "http://www.perlgurl.org/podcast/archives/podcasts/PerlgurlPromo.mp3";
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(url);
mp.prepare();
mp.start();
} catch (Exception e){
Log.e(DebugTag, "Error Playing File", e);
}
}
@Override
protected void onStop() {
if (mp != null) {
mp.stop();
mp.release();
}
super.onStop();
}
}
實施一些問題的答案之後,我現在得到這個錯誤:java.io.IOException: Prepare Failed .: status = 0x1
好的,我該如何處理它以使我能夠播放文件? –
由於@Ilango J注意下面,你需要調用mp.prepare();.我花了一些時間,看看在文檔中創建的流程圖,是我嗎:http://developer.android.com/reference/android/media/MediaPlayer.html – Paddy
也許有一些東西我沒有得到正確的,但沒有任何更改 –