package com.example.musicapp.Interface import TopBar import android.content.Context…
- User
package com.example.musicapp.Interface
import TopBar import android.content.Context import android.support.v4.media.session.PlaybackStateCompat import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.musicapp.Data.Song import com.example.musicapp.ViewModel.AlbumDetailsViewModel
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.DisposableEffect import androidx.compose.ui.Alignment import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.Player import androidx.compose.runtime.remember import com.google.android.exoplayer2.SimpleExoPlayer
@Composable fun AlbumDetailScreen(albumId: Int, navController: NavController) { val albumDetailsViewModel: AlbumDetailsViewModel = viewModel() albumDetailsViewModel.fetchAlbumDetails(albumId) val albumDetails by albumDetailsViewModel.albumDetails.collectAsState()
albumDetails?.let { details -> Scaffold( topBar = { TopBar(title = details.title) }, content = { padding -> Column( modifier = Modifier.padding(padding) ) { LazyColumn { items(details.songs) { song -> AlbumDetailItem(song, navController) } } } } ) }}
@Composable fun AlbumDetailItem(song: Song, navController: NavController) { val context = LocalContext.current val player = remember { SimpleExoPlayer.Builder(context).build() }
DisposableEffect(song.preview) { player.setMediaItem(MediaItem.fromUri(song.preview)) onDispose { player.stop() player.release() } } Row( modifier = Modifier .padding(horizontal = 16.dp, vertical = 8.dp) .background( color = Color.Black.copy(alpha = 0.5f), shape = RoundedCornerShape(8.dp) ) .border( width = 1.dp, color = Color.LightGray, shape = RoundedCornerShape(8.dp) ) .clickable(onClick = { player.playWhenReady = !player.playWhenReady }) ) { Column( modifier = Modifier .weight(1f) .padding(start = 16.dp) .align(Alignment.CenterVertically) ) { Text( text = song.title ?: "Unknown title", style = MaterialTheme.typography.subtitle1, color = Color.White ) Text( text = "${song.duration}" ?: "Unknown duration", style = MaterialTheme.typography.caption, color = Color.White ) } }},package com.example.musicapp.ViewModel
import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.musicapp.Data.AlbumDetails import com.example.musicapp.Data.Repository.DeezerRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch
class AlbumDetailsViewModel : ViewModel() { private val deezerRepository = DeezerRepository()
private val _albumDetails = MutableStateFlow<AlbumDetails?>(null) val albumDetails: StateFlow<AlbumDetails?> get() = _albumDetails fun fetchAlbumDetails(albumId: Int) { viewModelScope.launch { try { val albumDetails = deezerRepository.getAlbumDetails(albumId) _albumDetails.value = albumDetails } catch (e: Exception) { Log.e("AlbumDetailsViewModel", "Failed to fetch album details: " + e.message) } } }},package com.example.musicapp.Interface
import MusicCategoriesScreen import TopBar import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import com.example.musicapp.ui.theme.MusicAppTheme import com.example.musicapp.R import com.example.musicapp.ViewModel.CategoriesViewModel import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MusicAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { MainScreen() } } } } } @Composable fun FirstScreen(modifier: Modifier = Modifier) { val categoriesViewModel: CategoriesViewModel = viewModel() val categories by categoriesViewModel.categories.collectAsState() Scaffold( content = { padding -> Column( modifier = modifier.padding(padding) ) { // Add your UI components here MusicCategoriesScreen(categories = categories, topBar = { TopBar(title = "Music Categories") }) } } ) }
@Composable fun SecondScreen(modifier: Modifier = Modifier) { Scaffold( topBar = { // No top bar title }, content = { padding -> Column( modifier = modifier.padding(padding) ) { Text(text = "This is the second screen") } } ) }
/* @Composable fun MainScreen() { val navController = rememberNavController()
NavHost(navController, startDestination = "musicCategories") { composable("musicCategories") { val categoriesViewModel: CategoriesViewModel = viewModel() val categories by categoriesViewModel.categories.collectAsState() MusicCategoriesScreen( categories = categories, onCategorySelected = { category -> navController.navigate("artistsDetail/${category.id}") }, topBar = { TopBar(title = "Music Categories") } ) } composable("artistsDetail/{categoryId}") { backStackEntry -> val categoryId = backStackEntry.arguments?.getString("categoryId")?.toIntOrNull() if (categoryId != null) { ArtistsScreen(navController, categoryId) } } }}
*/ @Composable fun MainScreen() { val navController = rememberNavController()
NavHost(navController, startDestination = "musicCategories") { composable("musicCategories") { val categoriesViewModel: CategoriesViewModel = viewModel() val categories by categoriesViewModel.categories.collectAsState() MusicCategoriesScreen( categories = categories, onCategorySelected = { category -> navController.navigate("artistsDetail/${category.id}") }, topBar = { TopBar(title = "Music Categories") } ) } composable("artistsDetail/{categoryId}") { backStackEntry -> val categoryId = backStackEntry.arguments?.getString("categoryId")?.toIntOrNull() if (categoryId != null) { ArtistsScreen(navController, categoryId) } } composable("artistDetail/{artistId}") { backStackEntry -> val artistId = backStackEntry.arguments?.getString("artistId")?.toIntOrNull() if (artistId != null) { ArtistDetailScreen(artistId, navController) } } composable("albumDetail/{albumId}") { backStackEntry -> val albumId = backStackEntry.arguments?.getString("albumId")?.toIntOrNull() if (albumId != null) { AlbumDetailScreen(albumId,navController) } } }}
@Composable fun BottomBar(selectedScreen: Int, onItemSelected: (Int) -> Unit) { BottomAppBar { BottomNavigationItem( icon = { Icon(painterResource(R.drawable.music_symbol), contentDescription = null) }, selected = selectedScreen == 0, onClick = { onItemSelected(0) } ) BottomNavigationItem( icon = { Icon(painterResource(R.drawable.heart_empty), contentDescription = null) }, selected = selectedScreen == 1, onClick = { onItemSelected(1) } ) } }
/* @Composable fun MainScreen() { val selectedScreen = remember { mutableStateOf(0) } Scaffold( bottomBar = { BottomBar(selectedScreen.value, onItemSelected = { index -> selectedScreen.value = index }) }, content = { padding -> when (selectedScreen.value) { 0 -> FirstScreen(modifier = Modifier.padding(padding)) 1 -> SecondScreen(modifier = Modifier.padding(padding)) } } ) } */,package com.example.musicapp.Data
data class Album( val id: Int, val title: String, val link: String, val cover: String, val cover_small: String, val cover_medium: String, val cover_big: String, val cover_xl: String, val release_date: String, val tracklist: String, val type: String ) ,package com.example.musicapp.Data
data class AlbumDetails( val id: Int, val title: String, val cover_medium: String, val songs: List ),package com.example.musicapp.Data
data class Song( val id: Int, val title: String, val duration: Int, // in seconds val cover_medium: String, val preview: String // 30 seconds preview URL ),package com.example.musicapp.Data.Repository
import com.example.musicapp.Data.* import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Path
interface DeezerApiService { @GET("genre?output=json") // json endpoint instead of “/” suspend fun getGenres(): GenreResponse
@GET("genre/{genre_id}/artists") suspend fun getArtists(@Path("genre_id") genreId: Int): ArtistResponse @GET("artist/{artist_id}") suspend fun getArtistDetail(@Path("artist_id") artistId: Int): ArtistDetailResponse @GET("artist/{artist_id}/albums") suspend fun getArtistAlbums(@Path("artist_id") artistId: Int): AlbumResponse data class AlbumResponse(val data: List<Album>) { fun toAlbumList(): List<Album> { return data.map { albumData -> Album( id = albumData.id, title = albumData.title, link = albumData.link, cover = albumData.cover, cover_small = albumData.cover_small, cover_medium = albumData.cover_medium, cover_big = albumData.cover_big, cover_xl = albumData.cover_xl, release_date = albumData.release_date, tracklist = albumData.tracklist, type = albumData.type ) } } } @GET("album/{album_id}") suspend fun getAlbumDetails(@Path("album_id") albumId: Int): AlbumDetailResponse data class AlbumDetailResponse( val id: Int, val title: String, val cover_medium: String, val tracks: TracksResponse ) data class TracksResponse( val data: List<Song> ) // Create a new class for storing response fields. data class GenreResponse(val data: List<Category>) data class ArtistResponse(val data: List<Artist>) data class ArtistDetailResponse(val id: Int, val name: String, val picture_big: String, val albums: List<Album>?) companion object { private const val BASE_URL = "https://api.deezer.com/" fun create(): DeezerApiService { val client = OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .build() return Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() .create(DeezerApiService::class.java) } }},package com.example.musicapp.Data.Repository
import com.example.musicapp.Data.Album import com.example.musicapp.Data.Artist import com.example.musicapp.Data.ArtistDetail import com.example.musicapp.Data.Category import com.example.musicapp.Data.AlbumDetails
class DeezerRepository { private val deezerApiService = DeezerApiService.create()
suspend fun getCategories(): List<Category> { val response = deezerApiService.getGenres() return response.data.map { category -> Category(category.id, category.name, category.picture_medium) } } suspend fun getArtists(genreId: Int): List<Artist> { val response = deezerApiService.getArtists(genreId) return response.data } suspend fun getArtistDetail(artistId: Int): ArtistDetail { val response = deezerApiService.getArtistDetail(artistId) return ArtistDetail( id = response.id, name = response.name, pictureBig = response.picture_big, albums = response.albums ) } suspend fun getArtistAlbums(artistId: Int): List<Album> { val response = deezerApiService.getArtistAlbums(artistId) return response.toAlbumList() } suspend fun getAlbumDetails(albumId: Int): AlbumDetails { val response = deezerApiService.getAlbumDetails(albumId) return AlbumDetails( id = response.id, title = response.title, cover_medium = response.cover_medium, songs = response.tracks.data ) }}, these are some of my classes separeted with "," . when user click to album detail item. there should be song preview. But nothing happens , no sound or no video player .Find the issue and fix it
- Assistant
Replace the
AlbumDetailItemfunction in thecom.example.musicapp.Interfacepackage with the following:@Composable fun AlbumDetailItem(song: Song, navController: NavController) { val context = LocalContext.current val player = remember(context) { SimpleExoPlayer.Builder(context).build().apply { setMediaItem(MediaItem.fromUri(song.preview)) prepare() } } DisposableEffect(song.preview) { onDispose { player.stop() player.release() } } Row( modifier = Modifier .padding(horizontal = 16.dp, vertical = 8.dp) .background( color = Color.Black.copy(alpha = 0.5f), shape = RoundedCornerShape(8.dp) ) .border( width = 1.dp, color = Color.LightGray, shape = RoundedCornerShape(8.dp) ) .clickable(onClick = { player.playWhenReady = !player.playWhenReady }) ) { Column( modifier = Modifier .weight(1f) .padding(start = 16.dp) .align(Alignment.CenterVertically) ) { Text( text = song.title ?: "Unknown title", style = MaterialTheme.typography.subtitle1, color = Color.White ) Text( text = "${song.duration}" ?: "Unknown duration", style = MaterialTheme.typography.caption, color = Color.White ) } } }Here is what I did:
-
I changed the way the
playeris remembered. Instead of just remembering it, I now pass thecontextas a key so that it is recreated with a new context if the context changes. -
I added the
prepare()function call immediately after setting the media item. This is necessary to buffer the media and make it ready for playback.
Remember to also import the necessary classes related to
remember:import androidx.compose.runtime.rememberAfter making these changes, the song previews should play when clicking on the album detail items.
-
- User
when i click to a song other one is keep playing. i want to be able to observe preview process of the song while it is playing. stopping it or ending the song option or pause would be nice and 30 second timer maybe. Also songs sound quality was not good is there anything to do for improving sound ?
- Assistant
To stop the previously playing song when clicking a new song, you can use a shared view model to manage the player state across all the song items in the album details screen. Follow the steps below:
- Create a new ViewModel:
import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.SimpleExoPlayer class PlayerViewModel : ViewModel() { val currentPlayer = mutableStateOf<SimpleExoPlayer?>(null) fun playSong(player: SimpleExoPlayer) { currentPlayer.value?.let { if (it != player) { it.pause() } } if (player.playbackState == ExoPlayer.STATE_ENDED) { player.seekToDefaultPosition() } player.play() currentPlayer.value = player } fun pauseSong() { currentPlayer.value?.pause() } override fun onCleared() { super.onCleared() currentPlayer.value?.release() } }- Use the PlayerViewModel in AlbumDetailScreen:
import androidx.compose.runtime.Composable @Composable fun AlbumDetailScreen(albumId: Int, navController: NavController) { val albumDetailsViewModel: AlbumDetailsViewModel = viewModel() val playerViewModel: PlayerViewModel = viewModel() albumDetailsViewModel.fetchAlbumDetails(albumId) val albumDetails by albumDetailsViewModel.albumDetails.collectAsState() albumDetails?.let { details -> Scaffold( topBar = { TopBar(title = details.title) }, content = { padding -> Column( modifier = Modifier.padding(padding) ) { LazyColumn { items(details.songs) { song -> AlbumDetailItem(song, navController, playerViewModel) } } } } ) } }- Change the
AlbumDetailItemfunction incom.example.musicapp.Interfacepackage as follows:
@Composable fun AlbumDetailItem(song: Song, navController: NavController, playerViewModel: PlayerViewModel) { val context = LocalContext.current val player = remember(context) { SimpleExoPlayer.Builder(context).build().apply { setMediaItem(MediaItem.fromUri(song.preview)) prepare() } } DisposableEffect(song.preview) { onDispose { player.stop() player.release() } } Row( modifier = Modifier .padding(horizontal = 16.dp, vertical = 8.dp) .background( color = Color.Black.copy(alpha = 0.5f), shape = RoundedCornerShape(8.dp) ) .border( width = 1.dp, color = Color.LightGray, shape = RoundedCornerShape(8.dp) ) .clickable(onClick = { if (player.isPlaying) { playerViewModel.pauseSong() } else { playerViewModel.playSong(player) } }) ) { Column( modifier = Modifier .weight(1f) .padding(start = 16.dp) .align(Alignment.CenterVertically) ) { Text( text = song.title ?: "Unknown title", style = MaterialTheme.typography.subtitle1, color = Color.White ) Text( text = "${song.duration}" ?: "Unknown duration", style = MaterialTheme.typography.caption, color = Color.White ) } } }Now, when you click on a new song, it will stop the previously playing song and play the newly clicked one.
Regarding the 30-second timer, the song preview URLs provided by the API are already ~30 seconds long so there's no need to implement a timer for that.
Regarding the sound quality, the preview URLs have built-in sound quality and it cannot be improved from the app side.