2012-04-19 16 views
2

私はSDカードから曲を読み込んでリストビューに入れています。SDカードから取得したAndroidの曲

私はこの方法を使用しています。 ですが、時間がかかっていて、パスが違うとそのデータを取得できませんでした。

so、 QUE私のすべてのSDカードの曲を表示する便利なスクリプトはありますか? ディレクトリ/曲に入っている場合。

public ArrayList<HashMap<String, String>> getPlayList(){ 
     File home = new File(MEDIA_PATH); 

     if (home.listFiles(new FileExtensionFilter()).length > 0) { 
      for (File file : home.listFiles(new FileExtensionFilter())) { 
       HashMap<String, String> song = new HashMap<String, String>(); 
       song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4))); 
       song.put("songPath", file.getPath()); 

       // Adding each song to SongList 
       songsList.add(song); 
      } 
     } 
     // return songs list array 
     return songsList; 
    } 


    class FileExtensionFilter implements FilenameFilter { 
     public boolean accept(File dir, String name) { 
      return (name.endsWith(".mp3") || name.endsWith(".MP3")); 
     } 
    } 

これにご意見をお願いします。

+1

代わりhttp://stackoverflow.com/questions/5273519/accessing-music-files-into-my-をメディアストアのコンテンツプロバイダを使用しますアプリケーションプログラマチック – Pramod

答えて

1

このコードを使用してこの機能を実装してください。

public class SdCardSongsFragment extends Fragment { 
public File file; 
private List<String> myList; 
private List<String> mycountList; 
private ListView listView; 
private TextView pathTextView; 
private String mediapath = new String(Environment.getExternalStorageDirectory().getAbsolutePath()); 
String selection =MediaStore.Audio.Media.DATA +" like ?"; 
String[] projection = {MediaStore.Audio.Media.DATA , MediaStore.Audio.Media.DISPLAY_NAME}; 
Cursor cursor2; 
//your database elect statement 
String selection2 = MediaStore.Audio.Media.IS_MUSIC + " != 0"; 
//your projection statement 
String[] projection2= { 
     MediaStore.Audio.Media._ID, 
     MediaStore.Audio.Media.ARTIST, 
     MediaStore.Audio.Media.TITLE, 
     MediaStore.Audio.Media.DATA, 
     MediaStore.Audio.Media.DISPLAY_NAME, 
     MediaStore.Audio.Media.DURATION, 
     MediaStore.Audio.Media.ALBUM_ID 
}; 

private final static String[] acceptedExtensions= {"mp3", "mp2", "wav", "flac", "ogg", "au" , "snd", "mid", "midi", "kar" 
    , "mga", "aif", "aiff", "aifc", "m3u", "oga", "spx"}; 

/** Called when the activity is first created. */ 
@Override 

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.activity_sdcrad_song, container, false); 

    listView=(ListView) rootView.findViewById(R.id.pathlist); 
    pathTextView=(TextView) rootView.findViewById(R.id.path); 

    myList = new ArrayList<String>(); 
    mycountList= new ArrayList<String>(); 
    String root_sd = Environment.getExternalStorageDirectory().toString(); 
    Log.e("Root",root_sd); 

    String state = Environment.getExternalStorageState(); 
    File list[] = null ; 
    /* if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // we can read the External Storage... 
     list=getAllFilesOfDir(Environment.getExternalStorageDirectory()); 
    }*/ 

    pathTextView.setText(root_sd); 

    file = new File(root_sd) ;  
    list = file.listFiles(new AudioFilter()); 
    Log.e("Size of list ","" +list.length); 
    //LoadDirectory(root_sd); 

    for(int i=0; i< list.length; i++) 
    { 

     String name=list[i].getName(); 
     int count =  getAudioFileCount(list[i].getAbsolutePath()); 
     Log.e("Count : "+count, list[i].getAbsolutePath()); 
     if(count!=0) { 
      myList.add(name); 
      mycountList.add(""+count); 
     } 


    } 


    listView.setAdapter(new SDcardSongListAdapter(getActivity(), myList,mycountList)); 

    listView.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int position, 
       long arg3) { 
      File temp_file = new File(file, myList.get(position)); 

      if(!temp_file.isFile())   
      { 


       file = new File(file, myList.get(position)); 
       File list[] = file.listFiles(new AudioFilter()); 

       myList.clear(); 
       mycountList.clear(); 
       for(int i=0; i< list.length; i++) 
       { 
        String name=list[i].getName(); 

        int count =  getAudioFileCount(list[i].getAbsolutePath()); 
        Log.e("Count : "+count, list[i].getAbsolutePath()); 
        if(count!=0) { 
         myList.add(name); 
         mycountList.add(""+count); 
        } 

       } 

       pathTextView.setText(file.toString()); 
       //Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show(); 
       listView.setAdapter(new SDcardSongListAdapter(getActivity(), myList,mycountList)); 

      } 

      else { 
       Log.e("Not dirctory ", file.getAbsolutePath()); 
       Cursor cur=getAudioFileCursor(file.getAbsolutePath()); 
       Log.e("Cur count ", ""+cur.getCount()); 
       MusicUtils.playAll(getActivity(), cur,position); 
      } 


     } 
    }); 
    return rootView; 



} 

private int getAudioFileCount(String dirPath) { 

    Log.e("Path : ", dirPath); 
    String[] selectionArgs={dirPath+"%"}; 
    Cursor cursor = getActivity().managedQuery(
      MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
      projection2, 
      selection, 
      selectionArgs, 
      null); 


    cursor2=cursor; 
    if(cursor!=null) 
     Log.e("Cur : ", ""+cursor.getCount()); 
    return cursor.getCount(); 
} 

private Cursor getAudioFileCursor(String dirPath) { 


    String[] selectionArgs={dirPath+"%"}; 
    Cursor cursor = getActivity().managedQuery(
      MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
      projection2, 
      selection, 
      selectionArgs, 
      null); 
    return cursor; 
} 




public void onBack() { 
    String parent=""; 
    if(file!=null) 
     parent = file.getParent().toString(); 

    file = new File(parent) ;   
    File list[] = file.listFiles(new AudioFilter()); 

    myList.clear(); 
    mycountList.clear(); 
    for(int i=0; i< list.length; i++) 
    { 
     String name=list[i].getName(); 
     int count =  getAudioFileCount(list[i].getAbsolutePath()); 
     Log.e("Count : "+count, list[i].getAbsolutePath()); 
     if(count!=0) { 
      myList.add(name); 
      mycountList.add(""+count); 

     } 
     /*int count=getAllFilesOfDir(list[i]); 
      Log.e("Songs count ",""+count); 
      if(count!=0)*/ 

    } 
    pathTextView.setText(parent); 
    // Toast.makeText(getApplicationContext(), parent,   Toast.LENGTH_LONG).show(); 
    listView.setAdapter(new SDcardSongListAdapter(getActivity(), myList,mycountList)); 

} 



// class to limit the choices shown when browsing to SD card to media files 
public class AudioFilter implements FileFilter { 

    // only want to see the following audio file types 
    private String[] extension = {".aac", ".mp3", ".wav", ".ogg", ".midi", ".3gp", ".mp4", ".m4a", ".amr", ".flac"}; 

    @Override 
    public boolean accept(File pathname) { 

     // if we are looking at a directory/file that's not hidden we want to see it so return TRUE 
     if ((pathname.isDirectory() || pathname.isFile()) && !pathname.isHidden()){ 
      return true; 
     } 

     // loops through and determines the extension of all files in the directory 
     // returns TRUE to only show the audio files defined in the String[] extension array 
     for (String ext : extension) { 
      if (pathname.getName().toLowerCase().endsWith(ext)) { 
       return true; 
      } 
     } 

     return false; 
    }  
} 

}

XMLファイルのコード:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="@drawable/title_songs" 
android:orientation="vertical" > 

<TextView 
    android:id="@+id/pathDR" 
    android:layout_width="fill_parent" 
    android:layout_height="70dp" 
    android:layout_marginLeft="10dp" 
    android:layout_marginTop="10dp" 
    android:gravity="bottom" 
    android:text="Directory" 
    android:textColor="#ffffff" 
    android:textSize="19sp" 
    android:typeface="monospace" /> 

<TextView 
    android:id="@+id/path" 
    android:layout_width="fill_parent" 
    android:layout_height="18dp" 
    android:layout_marginBottom="10dp" 
    android:layout_marginLeft="10dp" 
    android:gravity="bottom" 
    android:text="" 
    android:textColor="#ffffff" 
    android:textSize="12sp" 
    android:typeface="monospace" /> 

<View 
    android:layout_width="fill_parent" 
    android:layout_height="2dp" 
    android:background="#ffffff" /> 

<ListView 
    android:background="@drawable/bg" 
    android:id="@+id/pathlist" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 
</ListView> 

</LinearLayout> 
5

私は以前、音楽アプリケーションにMediaStoreを使用しましたが、これはデータを取得してListViewを使用して表示するための非常に効率的で正しい方法です。これにより、SDカード上の任意のフォルダに保存されている音楽ファイルがすべて取得されます。

//your database elect statement 
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"; 
    //your projection statement 
    String[] projection = { 
      MediaStore.Audio.Media._ID, 
      MediaStore.Audio.Media.ARTIST, 
      MediaStore.Audio.Media.TITLE, 
      MediaStore.Audio.Media.DATA, 
      MediaStore.Audio.Media.DISPLAY_NAME, 
      MediaStore.Audio.Media.DURATION, 
      MediaStore.Audio.Media.ALBUM_ID 
    }; 
    //query 
    cursor = this.managedQuery(
      MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
      projection, 
      selection, 
      null, 
      null); 


    while(cursor.moveToNext()){ 
      songs.add(cursor.getString(0)); 
      songs.add(cursor.getString(1)); 
      songs.add(cursor.getString(2)); 
      songs.add(cursor.getString(3)); 
      songs.add(cursor.getString(4)); 
      songs.add(cursor.getString(5)); 
      album_id.add((long) cursor.getFloat(6)); 
    } 
    int a[]= new int[]{R.id.textView1 ,R.id.textView3};//, R.id.textview2}; 
    ListAdapter adapter = new SimpleCursorAdapter(this, 
      R.layout.items, cursor, new String[]{MediaStore.Audio.Media.TITLE,   MediaStore.Audio.Media.ARTIST/*, MediaStore.Audio.Media.DURATION*/} ,a); 
      setListAdapter(adapter); 
} 
+0

私のためにその仕事を願っています。 ありがとう。 –

+0

私のコードを別のファイルに置き換えるべきですか? 私はあなたの答えを受け入れるつもりですが、もし可能であれば、私のごみをもっと導くようにしてください。 このフィールドを初めて使っています。 –

+0

私のコードに置き換えてください。このコードをXMLのリストビューを含むあなたのアクティビティのoncreateの中に入れてください。 –

1
ArrayList<String> names = new ArrayList<String>(); 
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"; 
    Uri uri; 
    int columnIndex; 
    String[] projection = { MediaStore.Audio.Media._ID, 
      MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE, 
      MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DISPLAY_NAME, 
      MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM_ID }; 
    ListView lst; 
    ArrayAdapter<String> adapter; 
    Cursor cursor; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_home); 

     uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 

     cursor = this.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
       projection, selection, null, null); 

     if (cursor.getCount() == 0) { 

      Toast.makeText(getBaseContext(), 
        "cursor value" + cursor.getCount(), Toast.LENGTH_SHORT) 
        .show(); 
     } else { 

      cursor.moveToFirst(); 
      do { 
       names.add(cursor.getString(cursor 
         .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))); 

      } while (cursor.moveToNext()); 

      adapter = new ArrayAdapter<String>(Home.this, 
        android.R.layout.simple_list_item_1, names); 

      lst.setAdapter(adapter); 
     } 

これがお手伝いします私は私はSDカードにフォルダを追加し、実際にカーソル数0を取得していますが、ファイルは

0

//このその作業コードを試してみてください

public ArrayList<HashMap<String, String>> getAudioList() { 

    ArrayList<HashMap<String, String>> mSongsList = new ArrayList<HashMap<String, String>>(); 
    Cursor mCursor = getContentResolver().query(
      MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
      new String[] { MediaStore.Audio.Media.DISPLAY_NAME, 
        MediaStore.Audio.Media.DATA }, null, null, null); 

    int count = mCursor.getCount(); 
    System.out.println("total no of songs are=" + count); 
    HashMap<String, String> songMap; 
    while (mCursor.moveToNext()) { 
     songMap = new HashMap<String, String>(); 
     songMap.put(
       "songTitle", 
       mCursor.getString(mCursor 
         .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME))); 
     songMap.put("songPath", mCursor.getString(mCursor 
       .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))); 
     mSongsList.add(songMap); 
    } 
    mCursor.close(); 
    return mSongsList; 
} 
+0

この再生リストをリストビューで表示するにはどうすればいいですか? –

+0

Akshay Tyagiは私の下のコード に従ってください。 :) –

0

に来ていませんそのプレイリストを使用してリストビューを作成する

public class PlayListActivity extends ListActivity { 
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); 
private Context context; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.playlist); 
    EditText search = (EditText) findViewById(R.id.et_search_music); 
    ListView lv = (ListView) findViewById(android.R.id.list); 
    context = PlayListActivity.this; 
    ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>(); 
    this.songsList = MusicPlayerActivity.songsList; 
    if (this.songsList.size() > 0) { 
     final SimpleAdapter adapter = new SimpleAdapter(this, 
       this.songsList, R.layout.playlist_item, 
       new String[] { "songTitle" }, new int[] { R.id.songTitle }); 
     setListAdapter(adapter); 
     lv.setTextFilterEnabled(true); 
     lv = getListView(); 
     search.addTextChangedListener(new TextWatcher() { 

      @Override 
      public void onTextChanged(CharSequence s, int start, 
        int before, int count) { 
       adapter.getFilter().filter(s); 

      } 

      @Override 
      public void beforeTextChanged(CharSequence s, int start, 
        int count, int after) { 
       // TODO Auto-generated method stub 

      } 

      @Override 
      public void afterTextChanged(Editable s) { 
       // TODO Auto-generated method stub 

      } 
     }); 
     lv.setOnItemClickListener(new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       int CurrentSongIndex = position; 
       Intent in = new Intent(); 
       in.putExtra("songIndex", CurrentSongIndex); 
       setResult(100, in); 
       finish(); 
      } 
     }); 
    } 
} 

}

+0

インテントi =新しいインテント(this、PlayListActivity.class); startActivityForResult(i、100); これらの行でどこからでもPlaylistActivityを呼び出すことができます –

関連する問題