Search code examples
javaandroidkotlinaudio-streaming

How to play streamed URL link to mediaPlayer?


mediaPlayer won't play streamed radio link

my main goal is to make it so my android app can play a radio url link from radio-browser.info. Most of the answers i find are just using a regular .mp3 link, not a streamed audio. On top of that, i believe most answers i find are outdated so the code doesn't quite work.

This is what i have:

class MainActivity : AppCompatActivity() {
    private lateinit var testingButton : Button
    var mediaPlayer : MediaPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        testingButton = findViewById(R.id.testingButton)

        testingButton.setOnClickListener{
            playAudio()
        }
    }

    private fun playAudio() {
        mediaPlayer = MediaPlayer()
        try {
            mediaPlayer!!.setDataSource("http://play.sas-media.ru/play_256")
            mediaPlayer!!.prepareAsync()
            mediaPlayer!!.start()
        }catch (e: IOException) {
            e.printStackTrace()
        }
        Toast.makeText(this,"Audio started playing",Toast.LENGTH_LONG).show()
    }

The app doesn't crash upon button press, it says "Audio Started playing" but actually plays nothing. I feel like i'm missing something.

Edit: Logcat errors upon button press: MediaPlayerNative error (1, -2147483648) MediaPlayer error (1, -2147483648)

and if i press the button again after that error

MediaPlayer error (-38,0)


Solution

  • I think you are missing the below code in your playAudio() method

    mediaPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
    

    setAudioStreamType is deprecated updated code-

        private fun playAudio() {
        val audioAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
        GlobalScope.launch(Dispatchers.Main) {
            try {
                val mediaPlayer = MediaPlayer()
                withContext(Dispatchers.IO) {
                    mediaPlayer.setDataSource("https://play.sas-media.ru/play_256")
                    mediaPlayer.setAudioAttributes(audioAttributes)
                    mediaPlayer.prepare()
                }
                mediaPlayer.start()
                Toast.makeText(this@MainActivity, "Audio started playing", Toast.LENGTH_LONG).show()
            } catch (e: IOException) {
                e.printStackTrace()
                Toast.makeText(this@MainActivity, "Failed to play audio", Toast.LENGTH_LONG).show()
            }
        }
    }