2017-07-31 37 views
-2

我有問題 我想播放用戶選擇的音樂。這是我的代碼Mediaplayer無法正常工作。請幫助我

Button butt = (Button) findViewById(R.id.button2); 
    butt.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI); 
      startActivityForResult(intent, 10); 
     } 
    }); 

} 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    if (resultCode == RESULT_OK && requestCode == 10) { 
     Uri uriSound = data.getData(); 
     play(this, uriSound); 
    } 
} 

    private void play(Context context, Uri uri) { 

     try { 
      MediaPlayer mp = new MediaPlayer(); 
      mp.setDataSource(context, uri); 
      mp.start(); 
     } catch (IllegalArgumentException e) { 

      e.printStackTrace(); 
     } catch (SecurityException e) { 

      e.printStackTrace(); 
     } catch (IllegalStateException e) { 

      e.printStackTrace(); 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 
    } 

} 

但是當我選擇音樂時,它在我的活動中不起作用。我初學android系統,請幫我

+0

你得到哪些錯誤? –

+0

我沒有收到錯誤,但是當我從我的SD卡選擇音樂時,它不會在我的活動中播放。我有一本書,我想在我的書的所有活動中播放音樂 –

回答

0

下面的代碼使用它會工作

Intent intent = new Intent(); 
intent.setAction(android.content.Intent.ACTION_VIEW); 
File file = new File(YOUR_SONG_URI); 
intent.setDataAndType(Uri.fromFile(file), "audio/*"); 
startActivity(intent); 
+0

我希望我的應用能夠播放用戶喜歡的音樂。也許他們想在不同的路徑上播放不同的音樂作品 –

+0

您可以隨時定義URI –

+0

您能通過示例幫助我嗎?我不明白 –