線上音樂播放器主要包含三大模組:
implementation "com.google.android.exoplayer:exoplayer:2.19.1"
implementation "com.google.android.exoplayer:exoplayer-ui:2.19.1" // 含 PlayerView
<com.google.android.exoplayer2.ui.PlayerView
android:id="@+id/player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:controller_layout_id="@layout/custom_controller"
app:show_buffering="when_playing"
app:resize_mode="fit" />
SimpleExoPlayer player = new SimpleExoPlayer.Builder(context).build();
PlayerView playerView = findViewById(R.id.player_view);
playerView.setPlayer(player);
// 建立媒體項目 (支援 HTTP、HLS、DASH)
MediaItem mediaItem = MediaItem.fromUri("https://example.com/music.mp3");
player.setMediaItem(mediaItem);
player.prepare();
player.playWhenReady = true;
@Override
protected void onStart() {
super.onStart();
if (player != null) player.playWhenReady = true;
}
@Override
protected void onStop() {
super.onStop();
if (player != null) player.playWhenReady = false;
}
@Override
protected void onDestroy() {
super.onDestroy();
player?.release();
player = null;
}
// MediaSessionCompat 建立
MediaSessionCompat mediaSession = new MediaSessionCompat(this, "MusicService");
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
// 連結 ExoPlayer
MediaControllerCompat mediaController = new MediaControllerCompat(this, mediaSession.getSessionToken());
MediaControllerCompat.setMediaController(this, mediaController);
// 設定播放狀態、元資料、傳輸控制...
Cache cache = new SimpleCache(cacheDir, new LeastRecentlyUsedCacheEvictor(maxSize));
DataSource.Factory cacheFactory = new CacheDataSource.Factory()
.setCache(cache)
.setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory())
.setCacheWriteDataSinkFactory(new CacheDataSink.Factory());
player = new SimpleExoPlayer.Builder(context)
.setMediaSourceFactory(new DefaultMediaSourceFactory(cacheFactory))
.build();
ConcatenatingMediaSource playlist = new ConcatenatingMediaSource(
mediaSource1, mediaSource2, mediaSource3);
player.setMediaSource(playlist);
| 問題 | 可能原因 | 解決方案 |
|---|---|---|
| 播放卡頓 | 緩衝不足、網路不穩 | 啟用快取、調整緩衝參數、使用 CDN |
| 背景播放被系統殺掉 | 未使用 Foreground Service | 實作 MediaSession + Foreground Service |
| 特定格式無法播放 | 缺少解碼器、DRM 保護 | 確認格式支援、整合 Widevine/PlayReady |
| 音訊焦點搶佔 | 未處理 AudioFocus | 實作 AudioFocusRequest、暫停/降音邏輯 |