Android中设置铃声 [英] Setting Ringtone in Android

查看:167
本文介绍了Android中设置铃声的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/1271777/how-to-set-ringtone-in-android-from-my-activity">How从我的活动设置的铃声在Android中?

我在我的RES /原始文件夹中的声音文件,我想选择一个声音设置为一个按钮的点击铃声。难怪我怎么能做到这一点?

I have sounds files in my res/raw folder and i want to select a sound to set as a ringtone on the click of a button. Wonder how can i do that?

推荐答案

@Maxood

从@Clive的code是你所需要的设定铃声。你需要的绝对路径的文件,你不能从一个原始资源得到。

The code from @Clive is what you need to set the ringtone. You will need the absolute path to the file, which you can't get from a raw resource.

解决的办法是让资源文件的资产,并将其写入到SD卡1,你给它的内容解析为插入前。

The solution is to get the resource file asset and write it to the sdcard 1st, before you give it to the content resolver for insertion.

File newSoundFile = new File("/sdcard/media/ringtone", "myringtone.oog");
Uri mUri = Uri.parse("android.resource://com.your.package/R.raw.your_resource_id");
ContentResolver mCr = app.getContentResolver();
AssetFileDescriptor soundFile;
try {
       soundFile= mCr.openAssetFileDescriptor(mUri, "r");
   } catch (FileNotFoundException e) {
       soundFile=null;   
   }

   try {
      byte[] readData = new byte[1024];
      FileInputStream fis = soundFile.createInputStream();
      FileOutputStream fos = new FileOutputStream(newSoundFile);
      int i = fis.read(readData);

      while (i != -1) {
        fos.write(readData, 0, i);
        i = fis.read(readData);
      }

      fos.close();
   } catch (IOException io) {
   }

然后就可以使用previously发布解决方案

Then you can use the previously posted solution

       ContentValues values = new ContentValues();
   values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());
   values.put(MediaStore.MediaColumns.TITLE, "my ringtone");
   values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/oog");
   values.put(MediaStore.MediaColumns.SIZE, newSoundFile.length());
   values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
   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);

   Uri uri = MediaStore.Audio.Media.getContentUriForPath(newSoundFile.getAbsolutePath());
   Uri newUri = mCr.insert(uri, values);


   try {
       RingtoneManager.setActualDefaultRingtoneUri(getContext(), RingtoneManager.TYPE_RINGTONE, newUri);
   } catch (Throwable t) {
       Log.d(TAG, "catch exception");
   }

不要忘了写权限

Don't forget to write the the permission

&LT;使用-权限的Andr​​oid:名称=android.permission.WRITE_EXTERNAL_STORAG​​E/&GT;

在你的清单

希望这有助于

这篇关于Android中设置铃声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆