Android Tutorial MediaPlayer tutorial

The MediaPlayer is used to play audio files.
MediaPlayer supports formats like: mp3, midi, wave and ogg. The full list is available here: Android Supported Media Formats | Android Developers

In order to play an audio file we first need to load the file:
B4X:
MediaPlayer1.Load(File.DirAssets, "IsawHerStandingThere.mid")
In this case the file was added with the file manager and therefore File.DirAssets is used.

Now we can start playing the file with:
B4X:
MediaPlayer1.Play
and pause the playback with:
B4X:
MediaPlayer.Pause
Calling Play will resume from the same position.
Note that you can only call Pause while MediaPlayer is playing.

You can call MediaPlayer.Load at any point (after initialization), and load a new file.
MediaPlayer should be declared in Process_Globals otherwise a new instance will be created each time the activity is recreated.

The program attached is a small program that allows the user to see the playback progress and to change the position.

mediaplayer_1.png


This is the code:
B4X:
Sub Process_Globals
    Dim MediaPlayer1 As MediaPlayer
    Dim timer1 As Timer
End Sub

Sub Globals
    Dim barPosition As SeekBar
    Dim barVolume As SeekBar
    Dim lblPosition As Label
    Dim Looping As ToggleButton
End Sub

Sub Activity_Create(FirstTime As Boolean) 
    If FirstTime Then
        MediaPlayer1.Initialize( )
        MediaPlayer1.Load(File.DirAssets, "IsawHerStandingThere.mid")
        Timer1.Initialize("timer1", 1000)
    End If
    Activity.LoadLayout("1")
    Looping_CheckedChange(Looping.Checked) 'set the default value
End Sub

Sub Activity_Resume
    MediaPlayer1.Play
    timer1.Enabled = True
    timer1_Tick 'don't wait one second for the UI to update.
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If MediaPlayer1.IsPlaying Then MediaPlayer1.Pause
    timer1.Enabled = False
End Sub

Sub timer1_Tick
    If MediaPlayer1.IsPlaying Then
        barPosition.Value = MediaPlayer1.Position / MediaPlayer1.Duration * 100
        lblPosition.Text = "Position: " & ConvertToTimeFormat(MediaPlayer1.Position) & _
            " (" & ConvertToTimeFormat(MediaPlayer1.Duration) & ")"
    End If
End Sub
'converts milliseconds to m:ss format.
Sub ConvertToTimeFormat(ms As Int) As String
    Dim seconds, minutes As Int
    seconds = Round(ms / 1000)
    minutes = Floor(seconds / 60)
    seconds = seconds Mod 60
    Return NumberFormat(minutes, 1, 0) & ":" & NumberFormat(seconds, 2, 0) 'ex: 3:05
End Sub

Sub barVolume_ValueChanged (Value As Int, UserChanged As Boolean)
    MediaPlayer1.SetVolume(barVolume.Value / 100, barVolume.Value / 100)
End Sub

Sub barPosition_ValueChanged (Value As Int, UserChanged As Boolean)
    If UserChanged = False Then Return 'the value was changed programmatically
    MediaPlayer1.Position = Value / 100 * MediaPlayer1.Duration
    If MediaPlayer1.IsPlaying = False Then 'this can happen when the playback reached the end and the user changes the position
        MediaPlayer1.Play
    End If
    timer1_Tick 'immediately update the progress label
End Sub

Sub Looping_CheckedChange(Checked As Boolean)
    MediaPlayer1.Looping = Checked
End Sub
We are initializing MediaPlayer only once when the application starts.
Playing starts when the activity resumes, which happens right after the Create event.

A timer is used to check the playback position every second and update the label and seek bar.
Note that the seekbar ValueChanged position includes a boolean value named UserChanged which you can use to differentiate between changes done by the user (by dragging the thumb) and changes done programmatically.

The Looping property determines whether playback will restart automatically when it reaches the end.
 

Attachments

  • MediaPlayer.zip
    9.5 KB · Views: 6,201

Pelican104

New Member
Licensed User
Hi Erel,

Doesn't the android mediaplayer have an AudioSessionID property which can be used to attach effects to a mediaplayer?

I can find some references to a GetAudioSessionID method in the android API documentation but can't access the method in b4A.

Thanks
 

stevel05

Expert
Licensed User
You can get the audioSessionID via reflection:

B4X:
       Dim MP As Mediaplayer

       MP.Initialize

   Dim R As Reflector
   R.Target=MP
   R.Target=R.GetField("mp")
   AudioSessionID=R.RunMethod("getAudioSessionId")

The question is, what do you want to do with it? The Audio Effects API's are not currently available to B4A, unless I've missed a library which is more than possible of course.
 

Pelican104

New Member
Licensed User
Thanks Steve, that works perfectly.

I'd been attempting to do this using reflection but without any joy, I hadn't used the line

R.Target=R.GetField("mp")

What is that line doing?

I need the Audio Session ID for use with the UltimateAudio library, I wanted to generate a visualisation of a specific media player rather than the total output.

Thanks for your assistance that's been a great lesson on reflection as much as anything else.
 

stevel05

Expert
Licensed User
Within the B4A mediaplayerwrapper, the field mp holds the java mediaplayer object.

R.GetField("mp") gets its contents.

-------------------
Sent via Tapatalk
 
Last edited:

birnesoft

Active Member
Licensed User
Set stereo volume balance

is it possiple to set the left and right volume of the mediaplayer like with the audiotrack lib?
 

birnesoft

Active Member
Licensed User
It works

Yes it works!! :wav:
Wow Erel you are genial.

the value of the left and the right volume have to be
between 0 and 1

thanks much Björn
 

latch

Active Member
Licensed User
Is there an event that fires when the track ends or do you periodically check .isplaying to see if you need to load the next track?
 

stevel05

Expert
Licensed User
If you use Initialize2 the complete event is called when play is finished.

B4X:
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
Dim MP As MediaPlayer
End Sub

Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
'Do not forget to load the layout file created with the visual designer. For example:
'Activity.LoadLayout("Layout1")
MP.Initialize2("MP")
MP.Load(File.DirAssets,"file,mp3")
MP.Play
End Sub
Sub MP_Complete
   Log("Finished")
End Sub
 
Last edited:

aklisiewicz

Active Member
Licensed User
I have problem unziping this file.
Error:
! C:\INSTALLS\B4A\EXAMPLES\MediaPlayer.zip: Unknown method in
! C:\INSTALLS\B4A\EXAMPLES\MediaPlayer.zip: Unknown method in
! C:\INSTALLS\B4A\EXAMPLES\MediaPlayer.zip: Unknown method in
! C:\INSTALLS\B4A\EXAMPLES\MediaPlayer.zip: Unknown method in
! C:\INSTALLS\B4A\EXAMPLES\MediaPlayer.zip: No files to extract
 

texwillerx

Member
Licensed User
Using media player synchronously

I want to use media player.

My problem is that, I have to wait until the player finished the mp3 file.

I don't want to use a do loop.

Thanks and regards
 

rogeriosca

Member
Licensed User
The MediaPlayer is used to play audio files.
MediaPlayer supports formats like: mp3, midi, wave and ogg. The full list is available here: Android Supported Media Formats | Android Developers

In order to play an audio file we first need to load the file:
B4X:
MediaPlayer1.Load(File.DirAssets, "IsawHerStandingThere.mid")
In this case the file was added with the file manager and therefore File.DirAssets is used.

Now we can start playing the file with:
B4X:
MediaPlayer1.Play
and pause the playback with:
B4X:
MediaPlayer.Pause
Calling Play will resume from the same position.
Note that you can only call Pause while MediaPlayer is playing.

You can call MediaPlayer.Load at any point (after initialization), and load a new file.
MediaPlayer should be declared in Process_Globals otherwise a new instance will be created each time the activity is recreated.

The program attached is a small program that allows the user to see the playback progress and to change the position.

mediaplayer_1.png


This is the code:
B4X:
Sub Process_Globals
    Dim MediaPlayer1 As MediaPlayer
    Dim timer1 As Timer
End Sub

Sub Globals
    Dim barPosition As SeekBar
    Dim barVolume As SeekBar
    Dim lblPosition As Label
    Dim Looping As ToggleButton
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        MediaPlayer1.Initialize( )
        MediaPlayer1.Load(File.DirAssets, "IsawHerStandingThere.mid")
        Timer1.Initialize("timer1", 1000)
    End If
    Activity.LoadLayout("1")
    Looping_CheckedChange(Looping.Checked) 'set the default value
End Sub

Sub Activity_Resume
    MediaPlayer1.Play
    timer1.Enabled = True
    timer1_Tick 'don't wait one second for the UI to update.
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If MediaPlayer1.IsPlaying Then MediaPlayer1.Pause
    timer1.Enabled = False
End Sub

Sub timer1_Tick
    If MediaPlayer1.IsPlaying Then
        barPosition.Value = MediaPlayer1.Position / MediaPlayer1.Duration * 100
        lblPosition.Text = "Position: " & ConvertToTimeFormat(MediaPlayer1.Position) & _
            " (" & ConvertToTimeFormat(MediaPlayer1.Duration) & ")"
    End If
End Sub
'converts milliseconds to m:ss format.
Sub ConvertToTimeFormat(ms As Int) As String
    Dim seconds, minutes As Int
    seconds = Round(ms / 1000)
    minutes = Floor(seconds / 60)
    seconds = seconds Mod 60
    Return NumberFormat(minutes, 1, 0) & ":" & NumberFormat(seconds, 2, 0) 'ex: 3:05
End Sub

Sub barVolume_ValueChanged (Value As Int, UserChanged As Boolean)
    MediaPlayer1.SetVolume(barVolume.Value / 100, barVolume.Value / 100)
End Sub

Sub barPosition_ValueChanged (Value As Int, UserChanged As Boolean)
    If UserChanged = False Then Return 'the value was changed programmatically
    MediaPlayer1.Position = Value / 100 * MediaPlayer1.Duration
    If MediaPlayer1.IsPlaying = False Then 'this can happen when the playback reached the end and the user changes the position
        MediaPlayer1.Play
    End If
    timer1_Tick 'immediately update the progress label
End Sub

Sub Looping_CheckedChange(Checked As Boolean)
    MediaPlayer1.Looping = Checked
End Sub
We are initializing MediaPlayer only once when the application starts.
Playing starts when the activity resumes, which happens right after the Create event.

A timer is used to check the playback position every second and update the label and seek bar.
Note that the seekbar ValueChanged position includes a boolean value named UserChanged which you can use to differentiate between changes done by the user (by dragging the thumb) and changes done programmatically.

The Looping property determines whether playback will restart automatically when it reaches the end.


Thanks ! Works perfectly on DEFY.
 

Larry

New Member
Licensed User
I followed the code and installed it just the same. When I added an .mp3 file instead of the .mid file, it freezes up every time... Any suggestions?
 

imgsimonebiliato

Well-Known Member
Licensed User
Hello Erel,
how is it possible to set the sound, only when a button is long clicked?
 

Paul Edwards

Member
Licensed User
I've been working on a media player app. It works fine in the foreground, but stops when the phone goes to sleep. I know I need to add a Service Module so it can continue to play in the background. Is there an explanation of how to do this on this website?

Paul
 
Top