Android studio 开发一个音乐播放器 详细代码
时间: 2024-03-08 19:48:13 浏览: 302
很抱歉,由于篇幅限制,无法在此处提供完整的代码。但我可以为您提供一些核心代码片段和步骤:
1. 首先,在 build.gradle 中添加以下依赖:
```
dependencies {
implementation 'com.google.android.exoplayer:exoplayer:2.12.1'
}
```
2. 在您的布局文件中创建一个用户界面,包含播放/暂停按钮,歌曲名称、歌手和播放进度条。
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/song_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Song Title" />
<TextView
android:id="@+id/song_artist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Song Artist" />
<SeekBar
android:id="@+id/playback_seekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="@+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_play_arrow_black_24dp" />
<ImageButton
android:id="@+id/pause_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_pause_black_24dp" />
</LinearLayout>
</LinearLayout>
```
3. 创建一个数据模型来存储歌曲的信息,例如歌曲名称、歌手、专辑、时长和文件路径。
```
data class Song(
val title: String,
val artist: String,
val album: String,
val duration: Long,
val uri: Uri
)
```
4. 创建一个歌曲列表,并使用 RecyclerView 显示歌曲信息。
```
class SongListAdapter(
private val songs: List<Song>,
private val onItemClick: (Song) -> Unit
) : RecyclerView.Adapter<SongListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_song, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val song = songs[position]
holder.titleTextView.text = song.title
holder.artistTextView.text = song.artist
holder.itemView.setOnClickListener { onItemClick(song) }
}
override fun getItemCount(): Int = songs.size
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titleTextView: TextView = itemView.findViewById(R.id.song_title)
val artistTextView: TextView = itemView.findViewById(R.id.song_artist)
}
}
```
5. 创建一个音乐播放器服务,以便在后台播放音乐,并将其绑定到 Activity 中。
```
class MusicService : Service() {
private lateinit var exoPlayer: SimpleExoPlayer
private var currentSong: Song? = null
override fun onBind(intent: Intent): IBinder? = MusicBinder()
inner class MusicBinder : Binder() {
fun getService(): MusicService = this@MusicService
}
override fun onCreate() {
super.onCreate()
exoPlayer = SimpleExoPlayer.Builder(this).build()
}
override fun onDestroy() {
super.onDestroy()
exoPlayer.release()
}
fun play(song: Song) {
if (song != currentSong) {
currentSong = song
val mediaItem = MediaItem.fromUri(song.uri)
exoPlayer.setMediaItem(mediaItem)
exoPlayer.prepare()
}
exoPlayer.play()
}
fun pause() {
exoPlayer.pause()
}
fun seekTo(position: Long) {
exoPlayer.seekTo(position)
}
fun getCurrentPosition(): Long = exoPlayer.currentPosition
fun getDuration(): Long = exoPlayer.duration
fun isPlaying(): Boolean = exoPlayer.isPlaying
}
```
6. 在音乐播放器服务中实现播放、暂停、跳转到下一首和上一首歌曲的功能。
```
fun play(song: Song) {
if (song != currentSong) {
currentSong = song
val mediaItem = MediaItem.fromUri(song.uri)
exoPlayer.setMediaItem(mediaItem)
exoPlayer.prepare()
}
exoPlayer.play()
}
fun pause() {
exoPlayer.pause()
}
fun seekTo(position: Long) {
exoPlayer.seekTo(position)
}
fun skipToNext() {
val currentSongIndex = songs.indexOf(currentSong)
val nextSongIndex = (currentSongIndex + 1) % songs.size
val nextSong = songs[nextSongIndex]
play(nextSong)
}
fun skipToPrevious() {
val currentSongIndex = songs.indexOf(currentSong)
val previousSongIndex = if (currentSongIndex == 0) {
songs.size - 1
} else {
currentSongIndex - 1
}
val previousSong = songs[previousSongIndex]
play(previousSong)
}
```
7. 在 Activity 中实现与音乐播放器服务的通信,以便更新用户界面和处理用户的输入。
```
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var musicService: MusicService
private var isBound = false
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val binder = service as MusicService.MusicBinder
musicService = binder.getService()
isBound = true
}
override fun onServiceDisconnected(name: ComponentName?) {
isBound = false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val songList = listOf(
Song("Song 1", "Artist 1", "Album 1", 180000, Uri.parse("path/to/song1.mp3")),
Song("Song 2", "Artist 2", "Album 2", 240000, Uri.parse("path/to/song2.mp3")),
Song("Song 3", "Artist 3", "Album 3", 300000, Uri.parse("path/to/song3.mp3"))
)
val songListAdapter = SongListAdapter(songList) { song ->
musicService.play(song)
updateUI()
}
binding.songList.adapter = songListAdapter
binding.playButton.setOnClickListener {
musicService.play()
updateUI()
}
binding.pauseButton.setOnClickListener {
musicService.pause()
updateUI()
}
binding.playbackSeekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
if (fromUser) {
musicService.seekTo(progress.toLong())
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
}
override fun onStart() {
super.onStart()
bindService(Intent(this, MusicService::class.java), connection, Context.BIND_AUTO_CREATE)
}
override fun onStop() {
super.onStop()
if (isBound) {
unbindService(connection)
isBound = false
}
}
private fun updateUI() {
binding.playButton.isEnabled = !musicService.isPlaying()
binding.pauseButton.isEnabled = musicService.isPlaying()
binding.playbackSeekbar.max = musicService.getDuration().toInt()
binding.playbackSeekbar.progress = musicService.getCurrentPosition().toInt()
}
}
```
以上是一个简单的步骤和代码示例,希望对您有所帮助!
阅读全文
相关推荐
















