【问题标题】:Set a selected audio file as ringtone将选定的音频文件设置为铃声
【发布时间】:2014-02-13 21:03:27
【问题描述】:

我正在开发一个应用程序:我正在尝试将音频文件设置为铃声。
看了很多帖子,但没有人真正帮助我,所以我决定问这个问题。

单击按钮时我使用此代码:

@Override
    public void onClick(View v) {
Intent intent = new Intent();  
            intent.setAction(Intent.ACTION_GET_CONTENT);  
            intent.setType("audio/*");          
            startActivityForResult(Intent.createChooser(intent, "Choose Sound File"), Audio);
}

onActivityResult我正在尝试获取文件路径,然后使用以下代码将音频文件设置为铃声:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Audio && requestCode==RESULT_OK) {


          Uri s1 = data.getData();
          String s = s1.getPath(); 


        if(s!=null){    

            try {
                k = new File(new URI(s)); //(File k;)
            } catch (URISyntaxException e) {

                e.printStackTrace();
            }
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
                values.put(MediaStore.MediaColumns.TITLE, "My Song title");
                values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
                values.put(MediaStore.Audio.Media.ARTIST, "Some Artist");
                values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
                values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
                values.put(MediaStore.Audio.Media.IS_ALARM, false);
                values.put(MediaStore.Audio.Media.IS_MUSIC, false);

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

                RingtoneManager.setActualDefaultRingtoneUri(
                  MainActivity.this,
                  RingtoneManager.TYPE_RINGTONE,
                  newUri);   

        }

        }
}

很遗憾,这段代码不起作用。
我会很感激你的回答。对不起我的英语不好。

【问题讨论】:

    标签: android file android-intent uri ringtone


    【解决方案1】:

    我看到了很多帖子,但有人展示了我实际上应该做的事情。所以我决定创建这个完整的答案,其中我有我的问题的解决方案......

    这是我使用的MainActivity.java

    import java.io.File;
    import android.app.Activity;
    import android.content.ContentValues;
    import android.content.Intent;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.view.View;
    import android.widget.Button;
    
    public class MainActivity extends Activity {
        Button b;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
            b = (Button) findViewById(R.id.button2);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
    
                    Intent intent1 = new Intent();
                    intent1.setAction(Intent.ACTION_GET_CONTENT);
                    intent1.setType("audio/*");
                    startActivityForResult(
                        Intent.createChooser(intent1, "Choose Sound File"), 6);
                }
            });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == RESULT_OK && requestCode == 6) {
                Uri i = data.getData();  // getData
                String s = i.getPath(); // getPath
                File k = new File(s);  // set File from path
                if (s != null) {      // file.exists
    
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
                    values.put(MediaStore.MediaColumns.TITLE, "ring");
                    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
                    values.put(MediaStore.MediaColumns.SIZE, k.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(k
                        .getAbsolutePath());
                    getContentResolver().delete(
                        uri,
                        MediaStore.MediaColumns.DATA + "=\""
                                + k.getAbsolutePath() + "\"", null);
                    Uri newUri = getContentResolver().insert(uri, values);
    
                    try {
                        RingtoneManager.setActualDefaultRingtoneUri(
                            MainActivity.this, RingtoneManager.TYPE_RINGTONE,
                            newUri);
                    } catch (Throwable t) {
    
                    }
                }
            }
        }
    }
    

    最后,在AndroidManifest.xml 中添加这些权限非常重要,例如,如果您不添加写入外部存储的权限,您的应用会像我的一样崩溃..xD

    您需要什么:

    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    

    您可以在 Google Play 上试用我的应用:BackAtel Audio Manager

    希望对您有所帮助....我的问题现在解决了!!我希望我也解决了你的问题:))

    【讨论】:

    • 我可以设置铃声和通知等。但是设置中的铃声名称是“未知类型”写在那里,甚至铃声没有添加到默认铃声列表中,如何请解决这个问题。
    • @ZiaUrRahman 要在铃声列表中列出您需要将该文件复制到铃声文件夹中。
    • 对不起,这段代码对我不起作用,为什么你需要 WRITE_SETTINGS 权限@noobProgrammer
    【解决方案2】:

    我遇到了同样的问题,在任何地方都找不到答案。

    这是我使用的代码。

    @SuppressLint("SdCardPath")
    public class Content extends Activity {
    
    
    int selectedSoundId;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content);
    
        final MediaPlayer player = new MediaPlayer();
        final Resources res = getResources();
    
        //just keep them in the same order, e.g. button01 is tied to back to you
        final int[] buttonIds = { R.id.Button01, R.id.Button02, R.id.Button03, R.id.Button04, R.id.Button05, R.id.Button06,R.id.button1};
        final int[] soundIds = { R.raw.deargod, R.raw.donttalk, R.raw.lookat, R.raw.stop, R.raw.text,R.raw.john, R.raw.sherlock, };
    
    
    
        View.OnClickListener listener = new View.OnClickListener() {
    
            public void onClick(View v) {
    
    
    
                //find the index that matches the button's ID, and then reset
                //the MediaPlayer instance, set the data source to the corresponding
                //sound effect, prepare it, and start it playing.
                for(int i = 0; i < buttonIds.length; i++) {
    
                    if(v.getId() == buttonIds[i]) {
                        selectedSoundId = soundIds[i];
    
                        AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
                        player.reset();
    
                        try {
                            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        } catch (IllegalArgumentException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            player.prepare();
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        player.start();
                        break;
                    }
                }
            }
    
        };
    
    
    
    
    
        //set the same listener for every button ID, no need
        //to keep a reference to every button
        for(int i = 0; i < buttonIds.length; i++) {
            Button soundButton = (Button)findViewById(buttonIds[i]);
            registerForContextMenu(soundButton);
            soundButton.setOnClickListener(listener);
    
            // new code to prevent crash is below.
            if(soundButton!= null)
            {
                selectedSoundId = soundIds[1];
            }
    
        }
    
    
    
    }
    
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
    
     super.onCreateContextMenu(menu, v, menuInfo);
     menu.setHeaderTitle("Save as...");
     menu.add(0, v.getId(), 0, "Ringtone");
     menu.add(0, v.getId(), 0, "Notification");
    }
    
    @Override   
    public boolean onContextItemSelected(MenuItem item) { 
    
     if(item.getTitle()=="Ringtone"){function1(item.getItemId());}   
      else if(item.getTitle()=="Notification"){function2(item.getItemId());}  
      else {return false;}
     return true; 
    }
    
    public void function1(int id){  
    
        if 
         (savering(selectedSoundId)){   
          // Code if successful   
          Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); 
         }           
         else           
         { 
          // Code if unsuccessful   
          Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
         }
    
        }
        public void function2(int id){   
         if 
         (savenot(selectedSoundId)){   
          // Code if successful   
          Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show(); 
         }           
         else           
         { 
          // Code if unsuccessful   
          Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); 
         }
        }
    
    
    
    //Save into Ring tone Folder
    
    
    public boolean savering(int ressound){
        byte[] buffer=null;
        InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
        int size=50;
    
        try {
            size = fIn.available();
            buffer = new byte[size];
            fIn.read(buffer);
            fIn.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    
        String path="/sdcard/sounds/";
        String filename="Sherlock"+".mp3";
    
        boolean exists = (new File(path)).exists();
        if (!exists){new File(path).mkdirs();}
    
        FileOutputStream save;
        try {
            save = new FileOutputStream(path+filename);
            save.write(buffer);
            save.flush();
            save.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    
        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, "SHRingtone");
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
        values.put(MediaStore.Audio.Media.ARTIST, "Sherlock ");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        values.put(MediaStore.Audio.Media.IS_ALARM, false);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);
    
        Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
        getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
        Uri newUri = getContentResolver().insert(uri, values); 
        RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
    
    
    
         return true;
    
    }
    
    //Save in Notification Folder
    
    @SuppressLint("SdCardPath")
    public boolean savenot(int ressound){
        byte[] buffer=null;
        InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
        int size=50;
    
        try {
            size = fIn.available();
            buffer = new byte[size];
            fIn.read(buffer);
            fIn.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    
        String path="/sdcard/sounds/";
        String filename="Sherlock"+".mp3";
    
        boolean exists = (new File(path)).exists();
        if (!exists){new File(path).mkdirs();}
    
        FileOutputStream save;
        try {
            save = new FileOutputStream(path+filename);
            save.write(buffer);
            save.flush();
            save.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    
        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, "SHNotification");
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
        values.put(MediaStore.Audio.Media.ARTIST, "sherlock ");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        values.put(MediaStore.Audio.Media.IS_ALARM, false);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);
    
    
    
    
        Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
        getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
        Uri newUri = getContentResolver().insert(uri, values); 
        RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, newUri);
    
    
    
     return true; 
    
    
    
    }
    }
    

    【讨论】:

      【解决方案3】:

      将音频设置为铃声与在闹钟中设置铃声相同,代码如下:

       ContentValues values = new ContentValues(4);
      long current = System.currentTimeMillis();
      values.put(MediaStore.MediaColumns.DATA, path+audioname );
      values.put(MediaStore.MediaColumns.TITLE,  path+audioname );
      values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
      values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
      
      //new
      values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
      values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
      values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
      values.put(MediaStore.Audio.Media.IS_ALARM, true);
      values.put(MediaStore.Audio.Media.IS_MUSIC, false);  
      ///new
      
      // values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
      // ContentResolver contentResolver = getContentResolver();
      //Insert it into the database
      this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(path+audioname), values);
      //RingtoneManager.setActualDefaultRingtoneUri(Activity.this,
      //        RingtoneManager.TYPE_RINGTONE, newUri);
      sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+path+audioname
                + Environment.getExternalStorageDirectory())));
      
      // sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+editText1)));
      //Toast.makeText(this, "New Alarm Sound " + editText1 +format, Toast.LENGTH_LONG).show();
       }
      

      使用此代码可以将您的声音放入特定的 sd 卡文件夹中,然后
      将其设置为铃声和闹钟:

           values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
            values.put(MediaStore.Audio.Media.IS_ALARM, true);
      

      或者你可以关注一个完整的tutorial关于这个问题。

      【讨论】:

        猜你喜欢
        • 2011-06-03
        • 1970-01-01
        • 2021-03-02
        • 1970-01-01
        • 2011-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多