¿Cómo puedo guardar el archivo Text to Speech como formato .wav / .mp3 en Almacenamiento externo
Estoy haciendo una muestra de texto a voz aplicación, en este mi requisito es obtener un texto del usuario con EditText y guardar el texto de entrada como formato .wav / .mp3 y almacenado en almacenamiento externo . Utilicé el siguiente código para este proceso, pero no lo lograré.
Main.xml
- ¿Cómo agregar un sonido al motor pico TTS de Android?
- Android TTS Masculino Masculino Voz Cambio
- Resalte la palabra actual que el motor TTS está hablando
- Ejecución de TTS Android en un servicio
- NullPointerException durante el uso de TTS en CustomListview
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/editText1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textMultiLine" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save in Sdcard" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Play the text file" /> </LinearLayout>
TTS_AudioActivity.java
public class TTS_AudioActivity extends Activity { /** Called when the activity is first created. */ Button store, play; EditText input; String speakTextTxt; private TextToSpeech mTts; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); store = (Button) findViewById(R.id.button1); play = (Button) findViewById(R.id.button2); input = (EditText) findViewById(R.id.editText1); store.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub speakTextTxt = input.getText().toString(); HashMap<String, String> myHashRender = new HashMap<String, String>(); myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, speakTextTxt); String exStoragePath = Environment .getExternalStorageDirectory().getAbsolutePath(); File appTmpPath = new File(exStoragePath + "/sounds/"); appTmpPath.mkdirs(); String tempFilename = "tmpaudio.wav"; String tempDestFile = appTmpPath.getAbsolutePath() + "/" + tempFilename; mTts.synthesizeToFile(speakTextTxt, myHashRender, tempDestFile); } }); play.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub final MediaPlayer mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource("/sdcard/sounds/tmpaudio.wav"); } 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(); } mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.start(); mMediaPlayer .setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mMediaPlayer.stop(); } }); } }); } }
En esto, cuando hago clic en el botón Store, el texto de entrada debe estar almacenado como formato .wav, para esto he utilizado la guía de desarrollador de formularios de fragmentos de código. Una vez que se guardó correctamente, cuando hice clic en el botón Reproducir, el archivo guardado debe reproducirse. Cómo puedo conseguir esto. Gracias por adelantado.
- TTS omite al azar las primeras letras de la oración
- Problema con isSpeaking () cuando se utiliza Text-to-Speech en Android
- TextToSpeech.OnInitListener.onInit (int) que se llama continuamente
- Android llamada TTS en BroadcastReceiver
- TextToSpeech versión de compilación android no reproduce audio
- ¿Cuál es el flujo de audio predeterminado de TTS?
- ¿Cómo puedo guardar mi android tts salida en un archivo wav?
- UtteranceProgressListener no funciona para Android TTS
¿Intentaste usar la función:
public int synthesizeToFile (CharSequence text, Bundle params, File file, String utteranceId)
DOCUMENTACIÓN DEL API
El código sería algo como esto:
private void speakText(String text) { String state = Environment.getExternalStorageState(); boolean mExternalStorageWriteable = false; boolean mExternalStorageAvailable = false; if (Environment.MEDIA_MOUNTED.equals(state)) { // Can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // Can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Can't read or write mExternalStorageAvailable = mExternalStorageWriteable = false; } File root = android.os.Environment.getExternalStorageDirectory(); File dir = new File(root.getAbsolutePath() + "/download"); dir.mkdirs(); File file = new File(dir, "myData.mp3"); int test = m_TTS.synthesizeToFile((CharSequence) text, null, file, "tts"); }
Si todo funciona bien, la prueba variable debe ser 0.
RECUERDE ADICIONAR PERMISOS A SU MANIFIESTO:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Utilizar
MediaScannerConnection.scanFile((Context) (this), new String[] {destFileName}, null, null);
Vuelva a conectar USB a su dispositivo. El mío no mostró los archivos .wav hasta que lo hice. Como alternativa, utilice el archivo ASTRO para verlos.
- Caja de múltiples movimientos de Android en xml extraíble
- Actualizando la base de datos desde gridview usando un popup de alerta en android