如何使用按钮在Android中将声音设置为铃声?

时间:2015-04-24 06:47:54

标签: android android-mediaplayer android-source ringtone

我写了这个简单的Main.java,需要知道如何使用简单的代码将soundpool或mediaplayer设置为铃声。 直接问题是:按钮“b2”设置为铃声

stackoverflow中有很少的来源,但我无法理解它们中的任何一个。 提前谢谢

我的代码:

public class Main extends Activity implements OnClickListener{

SoundPool sp;
int dicesound;
Button play, setAsRingtone;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
    dicesound = sp.load(this, R.raw.onedice, 1);
    play = (Button) findViewById(R.id.b1);
    setAsRingtone = (Button) findViewById(R.id.b2);
    play.setOnClickListener(this);
    setAsRingtone.setOnClickListener(this);
}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    switch(v.getId()){

    case R.id.b1:
        sp.play(dicesound, 1, 1, 0, 0, 1);
        break;

    case R.id.b2:
        // HOW TO SET "dicesound" SOUND AS A RINGTONE ???
        break;
    }
}

}

2 个答案:

答案 0 :(得分:1)

请检查以下代码,希望它可以帮助您

将“com.example.sample”替换为您的包名

    Uri m_path = Uri.parse("android.resource://com.example.sample/" + R.raw.onedice);
RingtoneManager.setActualDefaultRingtoneUri(activity.this,RingtoneManager.TYPE_RINGTONE, m_path);

答案 1 :(得分:0)

首先您需要将您的声音文件(原始文件到SD卡)复制到SD卡蚂蚁,然后使用以下代码设置为铃声。:

String filepath ="/sdcard/myring.mp3";
File ringtoneFile = new File(filepath);



//To set a ringtone you have to add it to the database.

//否则不会设置也不会给出错误。

ContentValues content = new ContentValues();
content.put(<span id="IL_AD7" class="IL_AD">MediaStore</span>.MediaColumns.DATA,ringtoneFile.getAbsolutePath());
content.put(MediaStore.MediaColumns.TITLE, "test");

content.put(MediaStore.MediaColumns.SIZE, 215454);

content.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");

content.put(MediaStore.Audio.Media.ARTIST, "artist");

content.put(MediaStore.Audio.Media.DURATION, 230);

content.put(MediaStore.Audio.Media.IS_RINGTONE, true);

content.put(MediaStore.Audio.Media.IS_NOTIFICATION, <span id="IL_AD4" class="IL_AD">false</span>);

content.put(MediaStore.Audio.Media.IS_ALARM, false);

content.put(MediaStore.Audio.Media.IS_MUSIC, false);

将其插入数据库

Log.i(TAG, "the absolute path of the file is :"+ringtoneFile.getAbsolutePath());
Uri uri = MediaStore.Audio.Media.getContentUriForPath(
ringtoneFile.getAbsolutePath());

Uri newUri = context.getContentResolver().<span id="IL_AD5" class="IL_AD">insert</span>(uri, content);

ringtoneUri = newUri;

Log.i(TAG,"the ringtone uri is :"+ringtoneUri);

RingtoneManager.setActualDefaultRingtoneUri(context,
RingtoneManager.TYPE_RINGTONE,newUri);