Android Tutorial MediaPlayer tutorial

Discussion in 'Tutorials & Examples' started by Erel, Nov 14, 2010.

  1. Erel

    Erel Administrator Staff 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:
    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:
    and pause the playback with:
    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.


    This is the code:
    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( )
    File.DirAssets, "IsawHerStandingThere.mid")
    End If
    'set the default value
    End Sub

    Sub Activity_Resume
        timer1.Enabled = 
    '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 = 
    End Sub

    Sub timer1_Tick
    If MediaPlayer1.IsPlaying Then
            barPosition.Value = MediaPlayer1.Position / MediaPlayer1.Duration * 
            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, 10) & ":" & NumberFormat(seconds, 20'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
    End If
    '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.

    Attached Files:

    koaunglay, Vahid.m and rogeriosca like this.
  2. mjcoon

    mjcoon Well-Known Member Licensed User

    Aha; that would have saved all those boolean flags I had to invent for the same purpose in Basic4PPC programs!

    Vahid.m likes this.
  3. moster67

    moster67 Expert Licensed User

    Wow Eril - you are really spoiling us with goodies :icon_clap:

    I actually feel guilty asking you this after all things you have managed to include in B4A so far, but I am wondering if you are going to extend later on the Media-Library with video-support as well?
  4. Erel

    Erel Administrator Staff Member Licensed User

    Thanks. I believe that the video functionality will be added in the future.
  5. susu

    susu Well-Known Member Licensed User

  6. Erel

    Erel Administrator Staff Member Licensed User

    For now you will need to first download the file and then play it locally.
  7. susu

    susu Well-Known Member Licensed User

    I hope B4A will support it. Thanks Erel.
  8. derez

    derez Expert Licensed User


    When playing mp3 files the duration is about 6.7 times the correct duration, I haven't tested other types yet. :confused:

    edit: Now I'm more confused because I found that for that album I have the same problem with the PPC player, and for other albums there is no problem.

    I guess it needs more checking... maybe there are differences in the mp3 files based on the compression level ?
    Last edited: Dec 8, 2010
  9. Erel

    Erel Administrator Staff Member Licensed User

    Maybe there is a problem with the meta data stored in this specific album.
  10. peacemaker

    peacemaker Well-Known Member Licensed User

    So is MediaPlayer the part of Android ? Not an application that can be removed from rooted device wishing to have better player (and application using it hangs)?
  11. Erel

    Erel Administrator Staff Member Licensed User

    MediaPlayer doesn't refer to any application. It is a feature of the OS.
  12. susu

    susu Well-Known Member Licensed User

    Can you make MediaPlayer supports streaming data?
  13. karmacomposer

    karmacomposer Member Licensed User

    Great. I will need to use media player. Is video far off? I really would love to take advantage of video playback if possible.

    How is drag and drop utilized on Android devices? I would like someone to drag and drop a file from a file browser, put it on a track, ready for playback.

    Also, how would I create a 'snap to' grid? Any ideas?

  14. nfordbscndrd

    nfordbscndrd Well-Known Member Licensed User

    I just compiled the sample Media Player app to an Archos 70, having modified it to load an MP3 file already on the device. It starts okay, but then it pauses every 5 seconds or so. I stopped all other apps which were running on the A70 and it still does it.

    The music player that comes with the A70 works fine, but I have had issues with other music players that I've downloaded, so I assume it is an issue with the A70, unless you know of something I may be doing wrong.

    The only other thing I can think of is that the A70 has a 250GB hard drive which is where the MP3s are stored. I noticed that Media Player stops if I press the A70's Home button while A70's music player continues in the background, so it makes me wonder if Media Player pauses when the hard drive is accessed or some other background app does something while the A70 player doesn't.
  15. Erel

    Erel Administrator Staff Member Licensed User

    It sounds like a problem in this specific device.

    The MediaPlayer is paused in Sub Activity_Pause. Remove it and it will continue playing.
  16. wocmedia

    wocmedia New Member

    Just a simple question isn't enough change in this code line MediaPlayer1.Load(File.DirAssets, "IsawHerStandingThere.mid") the .mid with one video extension supported by android to get a file video played by mediaplayer?
  17. Erel

    Erel Administrator Staff Member Licensed User

    It will not work. An audio file is expected.
  18. nfordbscndrd

    nfordbscndrd Well-Known Member Licensed User

    Looks like it. I just got this info on the Archos forum (regarding media player on the Archos A70):

  19. susu

    susu Well-Known Member Licensed User

    Just wonder when will media player supports streaming file??? I wished it for a long time.
  20. StevieC

    StevieC Member Licensed User

    Hi Erel,
    Is it possible to speed up and slow down the audio? Not necessarily keeping the pitch the same (although that would be a nice option).
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice