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,133

hgperli

Member
Licensed User
that's what I'm calling:

MinMP3_Player.Load("smb://192.168.178.25/public/_MUSIK_/A/ABBA/Waterloo/19-Waterloo.mp3")
so path is "smb://192.168.178.25/public/_MUSIK_/A/ABBA/Waterloo/"
file is "19-Waterloo.mp3"

Sub Process_Globals
Dim MP3_Server As SMB
Dim MinMP3_Player As MediaPlayerStream
End Sub
Sub Activity_Create(FirstTime As Boolean)
MP3_Server.Initialize("MP3_Server")
MP3_Server.ListFiles("smb://192.168.178.25/public/_MUSIK_/A/ABBA/Waterloo/","*") '<--------- this works perfect: lists all files

MinMP3_Player.Initialize("MinMP3_Player")
MinMP3_Player.Load("smb://192.168.178.25/public/_MUSIK_/A/ABBA/Waterloo/19-Waterloo.mp3") '<-------- this doesn't work at all: only error message
End Sub
 

Amadea

New Member
Earlier I think I asked the question in the wrong section, so I go ahead and ask it here. How do I include the audio file in the project? Where should I copy it? When I copy it to the emulator, it puts it in the download folder. I'm totally baffled as to what I need to do to get it find the audio file.
 

DonManfred

Expert
Licensed User
Earlier I think I asked the question in the wrong section, so I go ahead and ask it here.
This is your first post here in the forum. so you did not ask somewhere else (maybe in another forum).

You should create a new thread for your issue describing what the problem is and what code you are using (maybe upload your project (in the ide file -> Export as zip)

hat I need to do to get it find the audio file.
Put the file into your files-directory of your project before compiling.

See the example code in Post #1 of this thread.

Dont use the Android emulator. It is slow, not reliable and not suggested to use.

Use a real Device instead. Or an VM like Genymotion.
 

Amadea

New Member
This is your first post here in the forum. so you did not ask somewhere else (maybe in another forum).

You should create a new thread for your issue describing what the problem is and what code you are using (maybe upload your project (in the ide file -> Export as zip)


Put the file into your files-directory of your project before compiling.

See the example code in Post #1 of this thread.

Dont use the Android emulator. It is slow, not reliable and not suggested to use.

Use a real Device instead. Or an VM like Genymotion.

Thank you very much. I'm now hearing something. :) I went ahead and deleted that question, it was in B4J section. BTW, I do use genymotion. Thanks again.
 

JonPM

Well-Known Member
Licensed User
For various audio files is it better to use different MediaPlayer objects (ie MP1, MP2, etc)? Or to have one MediaPlayer object and load the sound at the time needed (on button click for example)?
Also I use some of the same audio files across different activities. Should MP only be initialized and loaded in Main, or done in each activity?
 

AbbasMohammed

Member
Licensed User
hello,

I'm wondering where did you set the shapes of the seek bars ? I cant find it anywhere in the project!!!

thank you in advance
 

rtek1000

Active Member
Licensed User
Hello,

I would suggest to add in the usage hint text for MediaPlayer.Looping, explain that have been used after MediaPlayer.Load

I've tried using MediaPlayer.Looping before MediaPlayer.Load and it does not work.
 
Top