2013-04-15 76 views
1

我正在嘗試創建僅播放.mp3文件的媒體播放器。我創建並在我的應用程序中顯示的列表,但無法播放該歌曲。我被建議使用意圖,但我不知道該怎麼做。使用Intents播放音頻文件

這是代碼;

ListView list; 
Cursor cursor; 
int columnIndex; 
int count; 
private ArrayAdapter arrayAdapter; 
private Button dropbox; 

public MainActivity() 
{ 

} 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    dropbox = (Button) findViewById(R.id.dropbox); 
    list = (ListView) findViewById(android.R.id.list); 

    dropbox.setOnClickListener(new View.OnClickListener() 
    { 

     @Override 
     public void onClick(View v) 
     { 
      Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.dropbox.com")); 
      startActivity(i); 
     } 
    }); 

    String[] displayMusic = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME}; 

    cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, displayMusic, null, null, null); 

    //0 is the id for a mp3 file on the sd card 
    //1 is the file name of the mp3 file on the sd card 
    final ArrayList<String> listOfMp3s = new ArrayList<String>(); 
    final ArrayList<String> listOfIds = new ArrayList<String>(); 
    while (cursor.moveToNext()) 
    { 
     if(cursor.getString(1).endsWith("mp3")) 
     { 
      listOfMp3s.add(cursor.getString(1)); 
      listOfIds.add(cursor.getString(0)); 
     } 
    } 



    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listOfMp3s); 
    list.setAdapter(arrayAdapter); 
    list.setOnItemClickListener(new OnItemClickListener() 
    { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
     { 
      Intent songPageIntent = new Intent(getApplicationContext(), SongPage.class); 
          startActivity(songPageIntent); 
     } 
    }); 
} 
+0

http://developer.android.com/guide/topics/media/mediaplayer.html檢查鏈接 – Raghunandan

回答

1

嘗試這樣

String name = "http://dl.dropboxusercontent.com/sh/t0in0j8jgsr9wft/abc.mp2"; 
Uri a = Uri.parse(name); 

Intent viewMediaIntent = new Intent(); 
viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW); 
viewMediaIntent.setDataAndType(a, "audio/*");   
viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
startActivity(viewMediaIntent); 
0

試試這個:

public void audioPlayer(String path, String fileName){ 
    //set up MediaPlayer  
    MediaPlayer mp = new MediaPlayer(); 

    try { 
     mp.setDataSource(path+"/"+fileName); 
     mp.prepare(); 
     mp.start(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
}