需要帮助在Android中将mp3保存到SD卡

时间:2013-06-14 23:49:30

标签: android save mp3

我正在尝试让我的Android应用程序将mp3从应用程序保存到SD卡,以便稍后使用,但它不会将文件保存在手机中的任何位置。在我的AndroidManifest文件中,我有权编写外部存储空间。 这是我到目前为止的代码:

public void onClick(View v) {
        int ressound = R.raw.hodor1;
        saveas(ressound);
    }

public boolean saveas(int ressound){
     byte[] buffer=null;
     InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
     int size=0;

     //1st part
     try {
      size = fIn.available();
      buffer = new byte[size];
      fIn.read(buffer);
      fIn.close();
     } catch (IOException e) {
         Log.e(TAG, "IOException first part");
      return false;
     }

     String soundname = "hodor1";
     String filename = soundname +".mp3";
     String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
     File fullPath = new File(path, filename);

     boolean exists = (new File(path)).exists();
     if (!exists){new File(path).mkdirs();}

     //second part
     FileOutputStream save;
     try {
         save = new FileOutputStream(fullPath);
         save.write(buffer);
         save.flush();
         save.close();
     } catch (FileNotFoundException e) {
         Log.e(TAG, "FileNotFoundException in second part");
         return false;
     } catch (IOException e) {
         Log.e(TAG, "IOException in second part");
         return false;
     }    

     //not working
     //sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

     File k = new File(path, filename);

     ContentValues values = new ContentValues();
     values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
     values.put(MediaStore.MediaColumns.TITLE, soundname);
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
     values.put(MediaStore.Audio.Media.ARTIST, "Elvis");
     values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
     values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
     values.put(MediaStore.Audio.Media.IS_ALARM, true);
     values.put(MediaStore.Audio.Media.IS_MUSIC, false);

     //Insert it into the database
     Uri newUri = this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

     // set as ringtone
     //savetype = RingtoneManager.TYPE_RINGTONE;
     //RingtoneManager.setActualDefaultRingtoneUri(this, savetype, newUri);

     return true;
    }

1 个答案:

答案 0 :(得分:0)

Commonsware最准确地回答了我的帖子。 Environment.getExternalStoragePublicDirectory()应该与正确的编程技术一起使用,例如Logging和使用两个参数File构造函数。