B4A en español - Juan Antonio Villalpando
(BASIC4Android)
-- Tutorial de B4A --
Volver al índice del tutorial
____________________________
20.- Media Player (Sonido). SoundPool. Streaming.
- Bajar el código: MediaPlayer.zip
- Tutorial. Estudio del Media Player. SoundPool.
- Presentación.
- Vamos a crear un reproductor de sonido basado en el Media Player de Basic4Android..
1.- MediaPlayer
Creamos los controles
|
Este Media Player funciona con archivos de sonidos, pero no con archivos de vídeos.
|
Mediante el Designer insertamos:
Button1 Text: Play
Button2 Text: Pausa
Button3 Text: Stop
Label1 Text: Volumen
Label2 Text: Duración
Label3 Text: Posición actual
Label4 Text: Posicionar el sonido
ProgressBar1
SeekBar1 Max Value: 100
Seekbar2 Max Value: 100
ToggleButton1 Una vez Continuamente
Guardamos el Designer: File / Save / Layout
Nota: es conveniente hacer las pruebas de funcionamiento con archivos de sonido de poco tamaño, ya que el emulador tarda mucho tiempo en cargarlos.
La canción se encuentra en la subcarpeta
MediaPlayer/Files/test_cbr.mp3
|
Código del programa en Basic4Android
|
'Activity module
Sub Process_Globals
' Juan Antonio Villalpando
' juana1991@yahoo.com
' http://www.basic4ppc.com/android/help/mediaplayer.html
Dim Timer1 As Timer
End Sub
Sub Globals
Dim MP As MediaPlayer
Dim ToggleButton1 As ToggleButton
Dim Button1, Button2, Button3 As Button
Dim SeekBar1, SeekBar2 As SeekBar
Dim Label2, Label3 As Label
Dim ProgressBar1 As ProgressBar
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Layout") ' Cargamos el Designer
MP.Initialize
MP.Load(File.DirAssets, "test_cbr.mp3")
' El Timer1 lo utilizamos si queremos poner un ProgressBar1
' Cada 500 milisigundos consultará la posición y actualizará el ProgressBar1
Timer1.Initialize("Timer1", 500) ' 1000 = 1 segundo
Timer1.Enabled = True
End Sub
Sub Button1_Click
MP.play
' Duración del archivo. La duración está en milisegundos, así que la paso a minutos:segundos
Dim minutos, segundos As Int
segundos = Round(MP.duration / 1000)
minutos = Floor(segundos / 60) Mod 60
segundos = segundos Mod 60
Label2.Text = "Duración " & NumberFormat(minutos,1,0) & ": " & NumberFormat(segundos,2,0)
End Sub
Sub Button2_Click
MP.pause
End Sub
Sub Button3_Click
' Si hacemos un stop, deberemos de volver a cargas la canción
MP.stop
End Sub
Sub SeekBar1_ValueChanged (Value As Int, UserChanged As Boolean)
' Volumen del sonido
' Se podría haber puesto un SeekBar1 para el canal derecho y otro SeekBar2 para el canal izquierdo
MP.SetVolume(SeekBar1.Value/100, SeekBar1.Value/100)
' He dividido entre 100, porque el valor del volumen debe estar comprendido entre 0 y 1
' Y el valor Max del SeekBar1 lo he establecido en 100
End Sub
Sub ToggleButton1_CheckedChange(Checked As Boolean)
' Mediante un ToggleButton1 podemos hacer que se repita el sonido (o que no se repita)
If Checked = True Then
MP.Looping = True
Else
MP.Looping = False
End If
End Sub
Sub Timer1_tick
' En la ProgressBar podemos observar en qué posición se encuentra el sonido.
If MP.IsPlaying Then
ProgressBar1.Progress = MP.position / MP.duration * 100
' Posición actual del archivo. Está en milisegundos, así que la paso a minutos:segundos
Dim minutes, segundes As Int
segundes = Round(MP.position / 1000)
minutes = Floor(segundes / 60) Mod 60
segundes = segundes Mod 60
Label3.Text = "Posición actual " & NumberFormat(minutes,1,0) & ": " & NumberFormat(segundes,2,0)
End If
End Sub
Sub SeekBar2_ValueChanged (Value As Int, UserChanged As Boolean)
' Posiciona del sonido
If UserChanged = False Then Return
MP.position = Value / 100 * MP.duration
If MP.IsPlaying Then
MP.Play
End If
End Sub
|
________________________________
2.- Notas musicales. Biblioteca Audio. SoundPool.
- Con este código podemos hacer sonar las notas musicales.
- Pulsamos la combinacíón de teclas Ctrl F11, para poner el emulador en horizontal.
- Mediante el Designer creamos un "Layout", con siete botones Button1, Button2, Button3, Button4, Button5, Button6 y Button7.
- Creamos el programa y en su carpeta Files y guardamos las siguientes notas musicales: notas.zip
- Necesitamos activar la biblioteca Audio.
Código del programa en Basic4Android
|
Sub Process_Globals
' Juan Antonio Villalpando
' juana1991@yahoo.com
' marzo 2013
End Sub
Sub Globals
Dim sp As SoundPool
Dim doo, re, mi, fa, sol, la, si As Int
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Layout")
If FirstTime Then
sp.Initialize(7)
doo = sp.Load(File.DirAssets, "do.mp3")
re = sp.Load(File.DirAssets, "re.mp3")
mi = sp.Load(File.DirAssets, "mi.mp3")
fa = sp.Load(File.DirAssets, "fa.mp3")
sol = sp.Load(File.DirAssets, "sol.mp3")
la = sp.Load(File.DirAssets, "la.mp3")
si = sp.Load(File.DirAssets, "si.mp3")
End If
End Sub
Sub Button1_Click
sp.Play(doo, 1, 1, 1, 0, 1)
End Sub
Sub Button2_Click
sp.Play(re, 1, 1, 1, 0, 1)
End Sub
Sub Button3_Click
sp.Play(mi, 1, 1, 1, 0, 1)
End Sub
Sub Button4_Click
sp.Play(fa, 1, 1, 1, 0, 1)
End Sub
Sub Button5_Click
sp.Play(sol, 1, 1, 1, 0, 1)
End Sub
Sub Button6_Click
sp.Play(la, 1, 1, 1, 0, 1)
End Sub
Sub Button7_Click
sp.Play(si, 1, 1, 1, 0, 1)
End Sub
|
- Comentario.
- La biblioteca Audio, contiene el objeto SoundPool
- Este objeto se utiliza para lanzar sonidos cortos, como disparos, choques, notas musicales,...
- Podemos utilizar estos sonidos para juegos o para que se emita un sonido cuando se pulse un botón, por ejemplo.
________________________________
3.- Streaming de sonido.
En los foros encontramos distintas posibilidade para hacer streaming, buscar MediaPlayerStream de la librería de Audio.
Aquí voy a proponer otra manera de hacerlo, lo encontramos en esta página del foro.
Necesitamos la librería Streamer Library y este código que copio de la página anterior.
También necesitamos un layout llamado "Layout". con 4 botones (btnStart, btnStop, btnIsStreaming y btnPause), además de un Label llamado lblDuration.
Código del programa en Basic4Android
|
Sub Process_Globals
End Sub
Sub Globals
Dim newStream As Streamer
Dim lblDuration As Label
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Layout")
End Sub
Sub btnStart_Click
Dim THREE_GPP As Int
newStream.StartAudioStream("http://www.freewebs.com/thebirdsmedia/faint.mp3")
'http://www.freewebs.com/thebirdsmedia/faint.mp3
End Sub
Sub btnStop_Click
newStream.StopAudioStream()
End Sub
Sub btnIsStreaming_Click
If newStream.IsStreaming = True Then
Msgbox("test", "It's Streaming!")
Else
Msgbox("test", "Aw to bad!")
End If
End Sub
Sub btnPause_click
Dim test As Int
newStream.PauseStream()
lblDuration.text = newStream.AudioDuration
End Sub
|
________________________________
4.- Sonido Beep.
- Creamos un Layout llamado "Layout" con un Button1.
- Agregamos la librería Audio.
Código del programa en Basic4Android
|
Sub Process_Globals
End Sub
Sub Globals
Dim b As Beeper
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Layout")
b.Initialize(300, 500) '300 milliseconds, 500 hz
End Sub
Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Sub Button1_Click
b.Beep
End Sub
|
________________________________
|