我在raw-directory中有两个MP3文件。
当我按下按钮时,随机选择2个mp3文件中的一个并开始播放,显示歌曲的元信息(艺术家和标题)。但是当我再次按下按钮而另一首歌开始播放时,元数据仍然是相同的(第一首歌)。歌曲改变时它不会改变。 这是我的代码:
public class MainActivity extends Activity {
Button playList_Black;
TextView textView;
MediaPlayer mp;
ImageView cover;
Random r = new Random();
int [] playlist_Black = {R.raw.music_a, R.raw.music_b};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
playList_Black = (Button)findViewById(R.id.btn_black);
textView = (TextView)findViewById(R.id.textView1);
cover = (ImageView)findViewById(R.id.imageView1);
}
@SuppressLint("NewApi")
protected String loadMp3DataFile(int i, Context context) {
String mp3_parameter;
String uriPath = "android.resource://" + getPackageName() + "/raw/" +
getResources().getResourceEntryName(i);
Uri uri = Uri.parse(uriPath);
// load data file
MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(context, uri);
String artist = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
Log.e("artist2: ", artist);
String title = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
byte[] songCover = metaRetriever.getEmbeddedPicture();
if(songCover != null) {
cover.setImageBitmap(BitmapFactory.decodeByteArray(songCover, 0, songCover.length));
}
else {
cover.setImageResource(R.drawable.ic_launcher);
}
//return parameter
mp3_parameter = (artist + "\n" + title);
// close object
metaRetriever.release();
return mp3_parameter;
}
public void PlayMusic(int playlist) {
if(mp != null) {
if(mp.isPlaying()){
mp.stop();
mp.reset();
mp = MediaPlayer.create(getApplicationContext(), playlist);
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
else if(mp.isPlaying() == false) {
mp = MediaPlayer.create(getApplicationContext(), playlist);
mp.start();
}
}
else {
mp = MediaPlayer.create(getApplicationContext(), playlist);
mp.start();
}
}
public void PlaylistBlack(View v) {
int i = playlist_Black[r.nextInt(playlist_Black.length)];
textView.setText(loadMp3DataFile(i, getApplicationContext()));
Log.e("Ausgabe: ", "" + i);
Log.e("Ausgabe: ", "" + getResources().getResourceEntryName(i));
PlayMusic(i);
}
我做错了什么?任何解决方案和建议?提前谢谢。
答案 0 :(得分:0)
代码是正确的,它在模拟器上工作正常。但是当我在我的智能手机上运行项目时,我遇到了问题,我在上面提到过。它只显示了一首歌的相同元信息。任何解决方案,在智能手机上工作?