如何防止在音乐播放器应用程序中同时播放多首歌曲?

时间:2018-12-25 06:45:36

标签: android kotlin

我正在尝试构建音乐播放器应用,当我已经尝试播放另一首歌曲时遇到问题。 我希望我的应用停止播放已经运行的歌曲并开始播放新歌曲。 我从适配器类中将歌曲的详细信息作为一个捆绑包下载到我的songPlayingFragment中。我尝试实现pause(),stop()和release()方法。但是他们都不起作用。我相信我在错误的代码部分中实现了它们。 这是我的代码,没有实现任何上述方法。 解决这个问题将有很大帮助。谢谢。

播放片段的代码

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    audioManager = myActivity?.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    favouriteContent = EchoDatabase(myActivity)

    currentSongHelper = CurrentSongHelper()
    currentSongHelper?.isPlaying = true
    currentSongHelper?.isLoop = false
    currentSongHelper?.isShuffle = false

    var path:String?=null
    var songTitle:String?=null
    var songArtist:String?=null
    var songId:Long = 0

    try
    {
       path = arguments?.getString("path")
       songTitle = arguments?.getString("songTitle")
       songArtist = arguments?.getString("songArtist")
       songId = arguments?.getInt("songId")?.toLong() as Long
       currentPosition = arguments?.getInt("songPosition") as Int
       fetchSongs = arguments?.getParcelableArrayList("songData")

        currentSongHelper?.songPath = path
        currentSongHelper?.songTitle = songTitle
        currentSongHelper?.songArtist = songArtist
        currentSongHelper?.songId = songId
        currentSongHelper?.currentPosition = currentPosition

        updateTextViews(currentSongHelper?.songTitle as String,currentSongHelper?.songArtist as String)
    }
    catch (e:Exception)
    {e.printStackTrace()}
    mediaPlayer = MediaPlayer()
    mediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
    try
    {
        mediaPlayer?.setDataSource(myActivity, Uri.parse(path))
        mediaPlayer?.prepare()
    }
    catch(e:Exception)
    {e.printStackTrace()}

    mediaPlayer?.start()
    processInformation(mediaPlayer as MediaPlayer)



    if(currentSongHelper?.isPlaying as Boolean)
    {
        playPauseButton?.setBackgroundResource(R.drawable.pause_icon)
    }
    else
    {
        playPauseButton?.setBackgroundResource(R.drawable.play_icon)
    }
    mediaPlayer?.setOnCompletionListener {
        songOnComplete()
    }

和我的适配器类

package com.musicplayer.echo.adapters

类MainScreenAdapter(arrayList:ArrayList,_context:Context):RecyclerView.Adapter() {

var songDetails:ArrayList<Songs>?=null
var mContext: Context?=null

init
{
    this.songDetails = arrayList
    this.mContext = _context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder
{
     val itemView = LayoutInflater.from(parent?.context)
             .inflate(R.layout.row_custom_mainscreen,parent,false)

    return MyViewHolder(itemView)
}

override fun getItemCount(): Int
{
    if(songDetails==null)
        return 0
    else
        return (songDetails as ArrayList<Songs>).size
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int)
{
     val songObject = songDetails?.get(position)
     holder.trackTitle?.text = songObject?.songTitle
     holder.trackArtist?.text = songObject?.songArtist
     holder.contentHolder?.setOnClickListener({

         val songPlayingFragment = SongPlayingFragment()
         var args = Bundle()
         args.putString("songArtist",songObject?.songArtist)
         args.putString("songTitle",songObject?.songTitle)
         args.putString("path",songObject?.songData)
         args.putInt("songId",songObject?.songId?.toInt() as Int)
         args.putInt("songPosition",position)
         args.putParcelableArrayList("songData",songDetails)
         songPlayingFragment.arguments = args
         (mContext as FragmentActivity).supportFragmentManager
                 .beginTransaction()
                 .replace(R.id.details_fragment, songPlayingFragment)
                 .commit()
     })
}
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view)
{
    var trackTitle : TextView?=null
    var trackArtist : TextView?=null
    var contentHolder : RelativeLayout?=null

    init
    {
        trackTitle = view.findViewById(R.id.trackTitle)
        trackArtist = view.findViewById(R.id.trackArtist)
        contentHolder = view.findViewById(R.id.contentRow)
    }
}

}

1 个答案:

答案 0 :(得分:0)

只需重置Mediaplayer的状态,然后播放另一首歌曲,这是一个示例:

  /**
   * release media player
   */
  private fun reset() {
    stopUpdatePosition()
    mediaPlayer?.isPlaying?.run { mediaPlayer?.stop() }
    mediaPlayer?.reset()
    mediaPlayer = null
  }

  private fun play(source: String) {
      mediaPlayer = MediaPlayer()
      mediaPlayer?.run {
      isLooping = isRepeatOne
      setOnPreparedListener(this@AudioPlayerService)
      setOnCompletionListener(this@AudioPlayerService)

      // must prepare in another thread
      setDataSource(source)
      prepareAsync()
    }
  }

  reset()
  // source ~ http://xxxx.mp3
  play(source)