Question

I am developing android musical piano application. in which i am using soundpool to play audios but how can i record sound so that user can sing and record his own voice along with recording music beats

Était-ce utile?

La solution

Here are wo functions one for recording and other for playing

private void startRecord(){
      File file = new File(Environment.getExternalStorageDirectory(), "test.pcm"); 

      try {
       file.createNewFile();
       recording=true;
       OutputStream outputStream = new FileOutputStream(file);
       BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
       DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);

       int minBufferSize = AudioRecord.getMinBufferSize(SmpleRate, 
         AudioFormat.CHANNEL_IN_MONO, 
         AudioFormat.ENCODING_PCM_16BIT);

       short[] audioData = new short[minBufferSize];

       AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
               SmpleRate,
         AudioFormat.CHANNEL_IN_MONO,
         AudioFormat.ENCODING_PCM_16BIT,
         minBufferSize);

       AudioManager audio=(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
      audio.setMicrophoneMute(true);
       //int sessionId=audioRecord.getAudioSessionId();
     //  NoiseSuppressor.create(sessionId);
       audioRecord.startRecording();

       while(recording){
        int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
        for(int i = 0; i < numberOfShort; i++){
         dataOutputStream.writeShort(audioData[i]);
        }
       }

       audioRecord.stop();
       dataOutputStream.close();

      } catch (IOException e) {
       e.printStackTrace();
      }

     }


 void playRecord(){

  File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");

        int shortSizeInBytes = Short.SIZE/Byte.SIZE;

  int bufferSizeInBytes = (int)(file.length()/shortSizeInBytes);
  short[] audioData = new short[bufferSizeInBytes];

  try {
   InputStream inputStream = new FileInputStream(file);
   BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
   DataInputStream dataInputStream = new DataInputStream(bufferedInputStream);

   int i = 0;
   while(dataInputStream.available() > 0){
    audioData[i] = dataInputStream.readShort();
    i++;
   }

   dataInputStream.close();

   AudioTrack audioTrack = new AudioTrack(
     AudioManager.STREAM_MUSIC,
     SmpleRate,
     AudioFormat.CHANNEL_OUT_MONO,
     AudioFormat.ENCODING_PCM_16BIT,
     bufferSizeInBytes,
     AudioTrack.MODE_STREAM);

   audioTrack.play();
   audioTrack.write(audioData, 0, bufferSizeInBytes);


  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top