2012-01-04 9 views
6

Tengo un código para reproducir un archivo de audio .ogg, que descargué de Internet. No tengo errores, para que pueda ejecutarlo, pero luego la aplicación se bloquea:¿Cómo reproduzco un archivo de audio en Android?

package play.my.sound; 

import android.app.Activity; 
import android.media.AudioManager; 
import android.media.SoundPool; 
import android.media.SoundPool.OnLoadCompleteListener; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnClickListener; 

public class PlaySound2Activity extends Activity { 
private SoundPool soundPool; 
private int soundID; 
boolean loaded = false; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    View view = findViewById(R.id.textView1); 
    view.setOnClickListener((OnClickListener) this); 
    // Set the hardware buttons to control the music 
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC); 
    // Load the sound 
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); 
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { 
     public void onLoadComplete(SoundPool soundPool, int sampleId, 
       int status) { 
      loaded = true; 
     } 
    }); 
    soundID = soundPool.load("sound1.ogg", 1); 

} 

public boolean onTouch(View v, MotionEvent event) { 
    if (event.getAction() == MotionEvent.ACTION_DOWN) { 
     // Getting the user sound settings 
     AudioManager audioManager = (AudioManager) getSystemService (AUDIO_SERVICE); 
     float actualVolume = (float) audioManager 
       .getStreamVolume(AudioManager.STREAM_MUSIC); 
     float maxVolume = (float) audioManager 
       .getStreamMaxVolume(AudioManager.STREAM_MUSIC); 
     float volume = actualVolume/maxVolume; 
     // Is the sound loaded already? 
     if (loaded) { 
      soundPool.play(soundID, volume, volume, 1, 0, 1f); 
      Log.e("Test", "Played sound"); 
     } 
    } 
    return false; 
} 
} 

creo que tengo dos problemas:

  1. pongo esto en el archivo main.xml:

     
    <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <TextView android:text="Click on the screen to start playing" 
        android:id="@+id/textView1" android:layout_width="fill_parent" 
        android:layout_height="fill_parent"></TextView> 
    </LinearLayout> 
    
    Y yo no sé si es correcto

  2. Puse el archivo sound1.ogg en la carpeta workspace->SoundPlay2 porque en la carpeta res tuve problemas, y también, traté de ponerlo en las dos carpetas de res que existen.

Esto es de mi consola:

[2012-01-04 19:38:16 - PlaySound2] Failed to install PlaySound2.apk on device 'emulator-5554': timeout 
[2012-01-04 19:38:16 - PlaySound2] Launch canceled! 
[2012-01-04 19:47:33 - PlaySound2] Error in an XML file: aborting build. 
[2012-01-04 19:52:34 - PlaySound2] res\layout\main.xml:0: error: Resource entry main is already defined. 
[2012-01-04 19:52:34 - PlaySound2] res\layout\main.out.xml:0: Originally defined here. 
[2012-01-04 19:52:34 - PlaySound2] C:\Users\Natalia\workspace\PlaySound2\res\layout\main.out.xml:1: error: Error parsing XML: no element found 

Tomé este ejemplo de "Android Sounds - Tutorial". Quiero reproducir un archivo de audio, más específicamente, un archivo .wav.

No sé dónde puedo encontrar información sobre los archivos permitidos en la clase MediaPlayer y sus características (duración, frecuencia de muestreo ...) ¿Podría decirme dónde puedo encontrar esto?

+0

Este es el último error que tengo en mi log cat: E/AndroidRuntime (739): java.lang.RuntimeException: no se puede iniciar la actividad ComponentInfo {play.my.sound/play.my.sound.PlaySound2Activity}: java .lang.ClassCastException: play.my.sound.PlaySound2Activity no se puede convertir a android.view.View $ OnClickListener –

+0

¿por qué no simplemente busca en google para encontrar respuestas simples. una búsqueda simple de "Formatos de audio admitidos" en google arrojó http://developer.android.com/guide/appendix/media-formats.html. http://developer.android.com/guide/topics/media/mediaplayer.html – manjusg

Respuesta

1

Ejemplo para reproducir algún tipo de zumbador. En la carpeta en la carpeta res cruda Tengo un buzzer.wav

Método para jugar este timbre:

 /** 
* Method to play an alarm sound to signal half time or full time. 
*/ 
private void playAlarm() { 
    MediaPlayer mp = MediaPlayer.create(this, 
      R.raw.buzzer); 
    mp.start(); 
    mp.setOnCompletionListener(new OnCompletionListener() { 

     @Override 
     public void onCompletion(MediaPlayer mp) { 
      mp.release(); 
     } 

    }); 

} 
+0

¿Es este método solo para reproducir archivos .wav? ¿Dónde tengo que agregarlo en mi código? ¡¡Gracias!! –

+0

He hecho algo así pero he usado un archivo .ogg. Cuando introduzco un archivo .wav, no funciona. ¿Hay alguna especificación acerca de esto debo saber? ¡¡Gracias!! –

1

nunca he visto la clase soundpool antes, sin embargo, recomendaría el uso de una clase MediaPlayer:

mMediaPlayer = new MediaPlayer(this, R.raw.yourfile); 
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
mMediaPlayer.prepare(); 
mMediaPlayer.start(); 

Asegúrese de poner el archivo en la carpeta PROYECTO/res/prima/(o crearlo si no existe)

también hay algo mal con su main.xml. ¿Puedes por favor publicarlo?

+0

¿Podría decirme qué parte de mi código tengo que eliminar o cambiar para insertar eso? –

+0

Para ser honesto, si no sabes qué cambiar, no entiendes tu propio código. Borre todas las líneas que interactúen con su Soundpool y lea esto: http://developer.android.com/reference/android/media/MediaPlayer.html – Force

3

Crea una carpeta sin formato en la carpeta res y agrega tu archivo a ella. A continuación, reproducir el archivo usando

soundID = soundPool.load(R.raw.sound1, 1); 

Y también ver esto post para su problema main.xml.

+0

He escrito soundID = soundPool.load (R.raw.sound1, 1) ; pero aparece un error que he cambiado por soundID = soundPool.load (this, R.raw.sound1, 1); y no aparecen errores, sin embargo cuando lo ejecuto, la aplicación falla !! –

+0

view.setOnClickListener ((OnClickListener) this) ;. esta línea falla porque no ha implementado View.onclicklistner. implementa la interfaz View.onclicklistner para la actividad. – manjusg

+0

revise el tutorial de dónde tomó el código. ellos han implementado Ontouchlistener. Compare su código línea por línea. – manjusg

Cuestiones relacionadas