¿Cómo puedo reproducir archivos pcm
El siguiente código debe grabar audio y almacenarlo en una tarjeta SD en formato PCM. El código está trabajando conmigo, pero el archivo PCM no juega !!!!
Tengo este código de este enlace …. Android: grabación de audio utilizando audiorecord juego de clase como avance rápido
- Aplicación de grabadora de voz android
- Orientación personalizada de grabación de vídeo
- Cómo comprimir archivos WAV en android
- ¿Cómo mantener el tamaño de audio, reducido, mientras se graba en android?
- Grabación de vídeo de fondo en Android 4.0
Necesito jugar el archivo PCM ¿Cómo puedo hacer eso ??????
public class Audio_Record extends Activity { private static final int RECORDER_SAMPLERATE = 8000; private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO; private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; private AudioRecord recorder = null; private Thread recordingThread = null; private boolean isRecording = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setButtonHandlers(); enableButtons(false); int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); System.out.println("BUFFER SIZE VALUE IS " + bufferSize); } private void setButtonHandlers() { ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick); ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick); } private void enableButton(int id, boolean isEnable) { ((Button) findViewById(id)).setEnabled(isEnable); } private void enableButtons(boolean isRecording) { enableButton(R.id.btnStart, !isRecording); enableButton(R.id.btnStop, isRecording); } int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we // use only 1024 int BytesPerElement = 2; // 2 bytes in 16bit format private void startRecording() { recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement); recorder.startRecording(); isRecording = true; recordingThread = new Thread(new Runnable() { public void run() { writeAudioDataToFile(); } }, "AudioRecorder Thread"); recordingThread.start(); } private byte[] short2byte(short[] sData) { int shortArrsize = sData.length; byte[] bytes = new byte[shortArrsize * 2]; for (int i = 0; i < shortArrsize; i++) { bytes[i * 2] = (byte) (sData[i] & 0x00FF); bytes[(i * 2) + 1] = (byte) (sData[i] >> 8); sData[i] = 0; } return bytes; } private void writeAudioDataToFile() { // Write the output audio in byte String filePath = "/sdcard/voice8K16bitmono.pcm"; short sData[] = new short[BufferElements2Rec]; FileOutputStream os = null; try { os = new FileOutputStream(filePath); } catch (FileNotFoundException e) { e.printStackTrace(); } while (isRecording) { // gets the voice output from microphone to byte format recorder.read(sData, 0, BufferElements2Rec); System.out.println("Short wirting to file" + sData.toString()); try { // // writes the data to file from buffer // // stores the voice buffer byte bData[] = short2byte(sData); os.write(bData, 0, BufferElements2Rec * BytesPerElement); } catch (IOException e) { e.printStackTrace(); } } try { os.close(); } catch (IOException e) { e.printStackTrace(); } } private void stopRecording() { // stops the recording activity if (null != recorder) { isRecording = false; recorder.stop(); recorder.release(); recorder = null; recordingThread = null; } } private View.OnClickListener btnClick = new View.OnClickListener() { public void onClick(View v) { switch (v.getId()) { case R.id.btnStart: { enableButtons(true); startRecording(); break; } case R.id.btnStop: { enableButtons(false); stopRecording(); break; } } } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); } return super.onKeyDown(keyCode, event); } }
- Cómo grabar llamadas telefónicas en android?
- Medidor de VU (audio) al grabar audio en Android
- ¿Por qué `` OnInfoListener` de MediaRecorder no se llama en código inferior cuando se alcanza el tamaño máximo de archivo
- ¿Puede el emulador de Android grabar y reproducir audio utilizando hardware de PC?
- Muy mala calidad de audio grabado en mi droidx con MediaRecorder, ¿por qué?
- ¿Cómo evitar que el android invierta la imagen de la cámara frente a frente?
- Cómo grabar voz en android?
- Grabar sonido en Android y leer Amplitud
Por defecto, el reproductor multimedia de Android no reproduce archivos PCM. Ya sea
- Copiar desde su tarjeta SD a su computadora y jugar allí
- Escribe tu propio reproductor usando
AudioTrack
- Instalar una aplicación que reproduzca PCM
Aquí está un tutorial sobre cómo jugar PCM usando la clase AudioTrack
: ( http://jongladwin.blogspot.co.uk/2010/03/android-play-pcmwav-audio-buffer-using.html )
Windows Media Player debe ser capaz de jugar PCM, algunas alternativas se mencionan aquí: ( http://www.makeuseof.com/answers/play-pcm-file-pc/ )
Supongo que la mayoría de las aplicaciones para reproductores de música en Android soportarán PCM.
También utilicé su código, pero mi expediente de la voz era como un expediente del "zzzzz". Así que cambié un poco el código y ahora puedo escuchar sin problemas y distorsiones el registro tanto por smartphone como por PC (en este caso con Audacity). Este es mi código:
public class VoiceActivity extends Activity { private static final String TAG = "VoiceRecord"; private static final int RECORDER_SAMPLERATE = 8000; private static final int RECORDER_CHANNELS_IN = AudioFormat.CHANNEL_IN_MONO; private static final int RECORDER_CHANNELS_OUT = AudioFormat.CHANNEL_OUT_MONO; private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; private static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC; // Initialize minimum buffer size in bytes. private int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS_IN, RECORDER_AUDIO_ENCODING); private AudioRecord recorder = null; private Thread recordingThread = null; private boolean isRecording = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_voice); ((Button) findViewById(R.id.start_button)).setOnClickListener(btnClick); ((Button) findViewById(R.id.stop_button)).setOnClickListener(btnClick); enableButtons(false); } private void enableButton(int id, boolean isEnable) { ((Button) findViewById(id)).setEnabled(isEnable); } private void enableButtons(boolean isRecording) { enableButton(R.id.start_button, !isRecording); enableButton(R.id.stop_button, isRecording); } private void startRecording() { if( bufferSize == AudioRecord.ERROR_BAD_VALUE) Log.e( TAG, "Bad Value for \"bufferSize\", recording parameters are not supported by the hardware"); if( bufferSize == AudioRecord.ERROR ) Log.e( TAG, "Bad Value for \"bufferSize\", implementation was unable to query the hardware for its output properties"); Log.e( TAG, "\"bufferSize\"="+bufferSize); // Initialize Audio Recorder. recorder = new AudioRecord(AUDIO_SOURCE, RECORDER_SAMPLERATE, RECORDER_CHANNELS_IN, RECORDER_AUDIO_ENCODING, bufferSize); // Starts recording from the AudioRecord instance. recorder.startRecording(); isRecording = true; recordingThread = new Thread(new Runnable() { public void run() { writeAudioDataToFile(); } }, "AudioRecorder Thread"); recordingThread.start(); } private void writeAudioDataToFile() { //Write the output audio in byte String filePath = "/sdcard/8k16bitMono.pcm"; byte saudioBuffer[] = new byte[bufferSize]; FileOutputStream os = null; try { os = new FileOutputStream(filePath); } catch (FileNotFoundException e) { e.printStackTrace(); } while (isRecording) { // gets the voice output from microphone to byte format recorder.read(saudioBuffer, 0, bufferSize); try { // writes the data to file from buffer stores the voice buffer os.write(saudioBuffer, 0, bufferSize); } catch (IOException e) { e.printStackTrace(); } } try { os.close(); } catch (IOException e) { e.printStackTrace(); } } private void stopRecording() throws IOException { // stops the recording activity if (null != recorder) { isRecording = false; recorder.stop(); recorder.release(); recorder = null; recordingThread = null; PlayShortAudioFileViaAudioTrack("/sdcard/8k16bitMono.pcm"); } } private void PlayShortAudioFileViaAudioTrack(String filePath) throws IOException{ // We keep temporarily filePath globally as we have only two sample sounds now.. if (filePath==null) return; //Reading the file.. File file = new File(filePath); // for ex. path= "/sdcard/samplesound.pcm" or "/sdcard/samplesound.wav" byte[] byteData = new byte[(int) file.length()]; Log.d(TAG, (int) file.length()+""); FileInputStream in = null; try { in = new FileInputStream( file ); in.read( byteData ); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Set and push to audio track.. int intSize = android.media.AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS_OUT, RECORDER_AUDIO_ENCODING); Log.d(TAG, intSize+""); AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS_OUT, RECORDER_AUDIO_ENCODING, intSize, AudioTrack.MODE_STREAM); if (at!=null) { at.play(); // Write the byte array to the track at.write(byteData, 0, byteData.length); at.stop(); at.release(); } else Log.d(TAG, "audio track is not initialised "); } private View.OnClickListener btnClick = new View.OnClickListener() { public void onClick(View v) { switch (v.getId()) { case R.id.start_button: { enableButtons(true); startRecording(); break; } case R.id.stop_button: { enableButtons(false); try { stopRecording(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } } } }; // onClick of backbutton finishes the activity. @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); } return super.onKeyDown(keyCode, event); } }
Private void startRecording () {if (bufferSize == AudioRecord.ERROR_BAD_VALUE) Log.e (TAG, "Valor incorrecto para \" bufferSize \ ", los parámetros de grabación no son compatibles con el hardware");
if( bufferSize == AudioRecord.ERROR ) Log.e( TAG, "Bad Value for \"bufferSize\", implementation was unable to query the hardware for its output properties"); Log.e( TAG, "\"bufferSize\"="+bufferSize); // Initialize Audio Recorder. recorder = new AudioRecord(AUDIO_SOURCE, RECORDER_SAMPLERATE, AudioFormat.CHANNEL_CONFIGURATION_MONO, RECORDER_AUDIO_ENCODING, bufferSize); // Starts recording from the AudioRecord instance. recorder.startRecording(); isRecording = true; recordingThread = new Thread(new Runnable() { public void run() { writeAudioDataToFile(); } }, "AudioRecorder Thread"); recordingThread.start();
}
Reemplazar el código de grabación …
- Cómo distribuir una Biblioteca de Android
- ¿La carga útil 4096 bytes incluye la longitud registration_id?