android - 保存 android 特定的按钮声音

标签 android

我有一个音板,我正在尝试将声音保存为铃声或通知,但它每次都保存相同的声音,我认为这是从“这里有人可以阐明一些问题吗?认为它需要改变 R。 raw.sound1 因此它会提取单击哪个按钮以调出上下文菜单的声音。

我已经添加了循环和集成代码,使按钮能够以防万一。

编辑完整代码 - 错误:无法解析 selectedSoundId
:- 对于表示 selectedSoundId 的每三位代码

不确定我是否已经完成了这一点: 我在哪里以及如何添加它?

“int selectedSoundId”应该声明为类字段,以使其在每个类方法中都可访问。

public class Soundboard extends Activity {
 private SoundManager mSoundManager;

/** Called when the activity is first created. */
int selectedSoundId;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.soundboard);

    final MediaPlayer player = new MediaPlayer();
    final Resources res = getResources();

    //just keep them in the same order, e.g. button01 is tied to backtoyou
    final int[] buttonIds = { R.id.backdoors etc};
    final int[] soundIds = { R.raw.back_doors etc };

    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);
    }
}

@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   
  return false;      } 

 String path="/sdcard/media/audio/ringtones/";

 String filename="ohhh"+".ogg";


 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   
  return false;  
 } catch (IOException e) {
  // TODO Auto-generated catch block   
  return false;
 }
 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, "Ohhh Ringtone");   
 values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");   
 values.put(MediaStore.Audio.Media.ARTIST, "weee");   
 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
 this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

 return true; 
}

     //Save in Notification Folder

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

 try {
   size = fIn.available();   
   buffer = new byte[size];   
   fIn.read(buffer);   
   fIn.close(); 
 } catch (IOException e) { 
  // TODO Auto-generated catch block   
  return false;      } 

 String path="/sdcard/media/audio/notifications/";

 String filename="ohhh"+".ogg";

 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   
  return false;  
 } catch (IOException e) {
  // TODO Auto-generated catch block   
  return false;
 }
 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, "Ohhh Notification");   
 values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");   
 values.put(MediaStore.Audio.Media.ARTIST, "weee");   
 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
 this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

 return true;
}
}

最佳答案

我没看到你在哪里替换

的内容
R.raw.sound1

您将其作为参数传递,因此,正如我在您的代码中观察到的那样,您每次调用保存方法时都会保存相同的声音。

编辑:

  1. 创建一个 int 变量来保存关于最后选择的声音的信息:

    int selectedSoundId;

  2. 在 onClickListener 中将 selectedSoundId 设置为与当前按钮关联的声音 ID:

    if(v.getId() == buttonIds[i]) { selectedSoundId = soundIds[i]; //剩下的代码

  3. 将 selectedSoundId 传递给 savering 和 savenot 方法:

    保存(selectedSoundId); savenot(selectedSoundId);

希望这对您有所帮助。

编辑 2:我正在粘贴您的代码和我的更正。

广告 2。这是您需要保存有关当前声音 ID 的信息的部分。

final int[] buttonIds = { R.raw.sound1 "etc all buttons here"};
    final int[] soundIds = {R.raw.sound1 "etc all sounds here"};

    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;
                }
            }
        }
    };

广告 3。这是调用savering和savenot方法的部分。

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(); 
 }
}

关于android - 保存 android 特定的按钮声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753666/

相关文章:

android - 使用 Dagger 2 将属性注入(inject) ViewModel

android - Android 中 OpenGL ES2.0 中的平移功能

android - AWS Android SDK 示例中的 "the provided key element does not match the schema"

java - 将 Realm 变量从其他类传递到适配器中的 getView

android - 我在 recyclerview 中有 3 个按钮,它们的点击事件是在主要 Activity 上设置的,而不是在适配器类中设置的?

java - BiometricPrompt.AuthenticationResult 中的 CryptoObject 始终为 null

java - 我想在长按时删除 ListView 上的项目

android - 设置默认(未聚焦)TextInputLayout 提示 textSize

Android:在整个动画中保持图像可见

android - 为什么 "cocos compile -p android"给出 "The android command is no longer available."错误