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

Itila Tumer

Active Member
Licensed User
Longtime User
I made a default sound. but if I come back to main manu
it starts again. what should ı do for not coming back to that page and not to playing sound again.
 

Attachments

  • fd.PNG
    fd.PNG
    49.4 KB · Views: 418

klaus

Expert
Licensed User
Longtime User
You should define a process global variable like Dim IsInitialized = False As Boolean
And in Avtivity_Resume:
B4X:
Sub Activity_Resume
    If IsInitalized = False Then
        MediaPlayer1.Play
        IsInitalized = True
    End If
    Timer1.Enabled = True
End Sub
 

klaus

Expert
Licensed User
Longtime User
You should post this question in a new thread because it is not related to the subject of this thread.
In the other thread you should post the project as a zip file (IDE menu File / Export As Zip) it would be easier for us to help you.
 
Last edited:

jamesnz

Active Member
Licensed User
Longtime User
I have several screens in my app, most of the sounds are played in screen 2
when I hit the back button in screen 2 the sounds should stop. But they don't.
I have tried using maediaplayer.pause and mediaplayer.stop, and release, these work if I use a button, but not from the Activity Pause sub
Is there a work around for getting sounds to stop when users close a screen
 

jamesnz

Active Member
Licensed User
Longtime User
all of this code is in my 2nd activity, there are no other references to the media players
even when I quit the app, the sound continues till it finishes

B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim MediaPlayer1 As MediaPlayer
    Dim MediaPlayer2 As MediaPlayer
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("Display")

MediaPlayer1.Initialize
MediaPlayer2.initialize
End Sub

Sub Activity_Pause (UserClosed As Boolean)
If UserClosed Then
MediaPlayer2.pause
MediaPlayer1.stop
'MediaPlayer1.Release
End If

sub anothersub
    If c.windspeed_value> 10 Then
                MediaPlayer2.Load(File.DirAssets, "wind1.mp3")
                MediaPlayer2.Play
    end if
end sub
 

DarkAngel

Member
Licensed User
Longtime User
Hello Erel,

First of all I apologize for my writing, since I’m Portuguese, some errors may occur

This is my first post, and I wonder if anyone else have the same issue.

When I play an mp3 file I ear noises (itchs or clicks) and it’s random.
If the file is longer it plays those noises every second or so, when the file is smaller sometimes it does not plays those noises, sometimes on the beginning of the audio.
I’m testing the app on a Galaxy S4 LTE.

Could you please help me with this?

Thank you.
 

DarkAngel

Member
Licensed User
Longtime User
Does it happen with a specific audio file or with all files?
I’ve been using two audio files and both act the same way. These files play just fine on any other player. Could it be related with the bit rate of the audio files?

One is 20kbs the other 80kbs.


Thank you.
 

DarkAngel

Member
Licensed User
Longtime User
The native media player is handling the audio files. The behavior should be the same as with any player that is based on the native media player.

I´ve been testing and found that the issue was with the files.

Thank you Erel :)
 

Indy

Active Member
Licensed User
Longtime User
Hi Erel,

I think there is an issue with the mp.duration method. It seems ok with relatively small files but, I tested it against an mp3 that is 1:35:40sec long and it reports the incorrect duration in millieseconds. I get 22769144 as the value. When you convert that using the various techniques sought on the Internet, they seem to suggest the file is over 6 hours long. I even tried the conversion with Google's online calculator and it's wrong. Any idea why this might be the case?

Thanks
 

hgperli

Member
Licensed User
Longtime User
For now you will need to first download the file and then play it locally.

Hi Erel, lost in the various questions & comments on streaming audio files from a server I came across this one.
as I read, in 2010 the feedback was that "For now you will need to first download the file and then play it locally".
Now 4 years later, is there a way to stream audio files without copying them first to the device? Would you mid attaching an executable example (please note that I'm programming only occasionally, with in fact little experience with net-work stuff)
Best Heinz-Georg
 

hgperli

Member
Licensed User
Longtime User
You can use MediaPlayerStream from the Audio library to stream audio files.
Thanks, but I'm pretty much puzzled (as mentioned: no idea about net-work stuff):
the attached program accesses my netdrive (192.168.178.1), and perfectly lists in step 1 (MP3_Server.ListFiles) the files in this directory, so access apparently works. however, when I try to stream one of the mp3's there it always ends up in a streaming error
any idea what I'm doing wrong - respectively: what is the correct path to enter in MinMP3_Player.Load() as url?
 

Attachments

  • for_erel.txt
    1.9 KB · Views: 407
Top