我正在尝试从URL获取流,但是我不断收到无法从数据源初始化错误
这是我的代码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val url = "http://www.radioideal.net:8026/;stream/1"
try {
val mediaPlayer: MediaPlayer? = MediaPlayer().apply {
setAudioStreamType(AudioManager.STREAM_MUSIC)
setDataSource(url)
prepareAsync()
start()
}
} catch (e: Exception) {
e.message
}
}
这是最简单的例子。
答案 0 :(得分:1)
您正在prepareAsync()之后立即调用start,这可能会引起问题。请使用下面的代码
override fun onCreate(savedInstanceState: Bundle?) {
val url = "http://www.radioideal.net:8026/;stream/1"
try {
val mediaPlayer: MediaPlayer? = MediaPlayer().apply {
setAudioStreamType(AudioManager.STREAM_MUSIC)
setDataSource(url)
setOnPreparedListener(this@MainActivity)
prepareAsync()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onPrepared(mp: MediaPlayer?) {
mp?.start()
}
别忘了实现MediaPlayer.OnPreparedListener...。干杯
答案 1 :(得分:0)
class MainActivity : AppCompatActivity(), MediaPlayer.OnPreparedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
play_btn.setOnClickListener {
val mp = MediaPlayer ()
mp.setOnPreparedListener(this@MainActivity)
try {
mp.setDataSource ("https://www.ssaurel.com/tmp/mymusic.mp3")
mp.prepareAsync ()
} catch (e: IOException) {
}
Toast.makeText (this, "Wait a moment while loading the mp3", Toast.LENGTH_SHORT) .show ()
}
}
override fun onPrepared (p0: MediaPlayer?) {
p0?.start()
}
}