Android Question How to play audio URI? [SOLVED]

JohnC

Well-Known Member
Licensed User
I am using the Phone.RingtoneManager to allow the user to select a sound for an alarm app, and it returns a URI of the selected sound.

Yes, the RingtoneManager does have a ".Play" method that will take a URI. But it does not have a ".Stop" method to stop playing long sound files. Yeah, I might be able to find a way to kill the RM object to stop it, but that is ugly.

The MediaPlayer requires separate Directory and File parameters, so it can't take a URI. Yes there are examples of how to extract the directory and filenames from a URI, but it's not guaranteed to work.

So, is there a way an alarm app can play the selected sound URI and then stop playing it on demand?
 

JohnC

Well-Known Member
Licensed User
This is nuts - If I select a long alarm sound, it will continuously play, and if I select another alarm file, BOTH will continuously play and I have to kill the app to stop them!

I am using the below code which is a slight variation to the example code posted here:

 
Last edited:

JohnC

Well-Known Member
Licensed User
Ok, here is the solution...

B4X:
Sub cmdReminderPick_Click
    rm.ShowRingtonePicker("rm", Bit.Or(rm.TYPE_ALARM,rm.TYPE_NOTIFICATION), True, AlarmURI)
End Sub

Sub rm_PickerResult (Success As Boolean, Uri As String)
    Dim j As JavaObject
  
    If Success Then
        If Uri = "" Then
            ToastMessageShow("Silent was chosen", True)
        Else
            Log(Uri)
            AlarmURI = Uri    'save for later when call showringtonepicker, it will pre-select same sound
            'rm.Play(Ur)
            J = GetRingtoneObject(Uri)
            J.RunMethod("play", Null)
            Sleep(2000)
            J.RunMethod("stop", Null)
        End If
    Else
        Log("Error_URI: " & Uri)
        ToastMessageShow("Error loading ringtone.", True)   'this will also trigger if user select same previous sound
    End If
End Sub

Sub GetRingtoneObject(Url As String) As JavaObject
    Dim jo As JavaObject
    Dim Jo2 As JavaObject
    Dim Ur As Uri
  
    jo.InitializeStatic("android.media.RingtoneManager")
    Jo2.InitializeContext
    Ur.Parse(Url)
    Return jo.RunMethodJO("getRingtone", Array(Jo2, Ur))
End Sub
 
Last edited:

JohnC

Well-Known Member
Licensed User
Top