我正在尝试创建一个从.pls文件播放互联网广播流的应用。我知道Android Media Player无法读取.pls文件,所以我事先读了它并获得了存储在.pls文件中的URL。那是我传递给setDataSource()的R.String.audio_stream
变量中的内容。但是,当我在模拟器上运行我的代码时,当我尝试启动媒体播放器时,它会失败。 LogCat返回错误消息,"无法创建媒体播放器。"有谁知道可能是什么问题?
这是我的代码:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
import android.media.MediaPlayer;
import android.util.Log;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
private Button mStartButton;
private Button mStopButton;
boolean isPlaying = false;
private static final String TAG = "MyActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mp = new MediaPlayer();
mStartButton = (Button)findViewById(R.id.start_button);
mStartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isPlaying){
//do nothing
}else{
isPlaying = true;
try{
mp.setDataSource(getString(R.string.audio_stream));
mp.prepare();
mp.start();
}catch(IOException e){
Log.e(TAG, "prepare() failed.");
}
}
}
});
mStopButton = (Button)findViewById(R.id.stop_button);
mStopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!isPlaying){
//do nothing
}else{
isPlaying = false;
mp.release();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:1)
很容易。您必须在" setDataSource":
之前使用mp.setAudioStreamType(AudioManager.STREAM_MUSIC);