gpt4 book ai didi

java - 播放文件时出错 : NullPointerException in Android

转载 作者:行者123 更新时间:2023-12-01 15:46:57 25 4
gpt4 key购买 nike

我想在 android 中播放 mp3 文件,但出现此错误:

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

我该如何解决这个错误?

谢谢

更新

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:准备失败.: status = 0x1

最佳答案

在 mp.start(); 之前添加 mp.prepare();

关于java - 播放文件时出错 : NullPointerException in Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6909101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com