index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MusicKit Minimal Test</title>
<!-- Load MusicKit JS v3 -->
<script src="https://js-cdn.music.apple.com/musickit/v3/musickit.js" data-web-components async></script>
</head>
<body>
<!-- Minimal UI -->
<button id="authorize-btn">Authorize Apple Music</button>
<button id="play-preview-btn">Play Preview</button>
<script>
// Wait for MusicKit to finish loading
document.addEventListener('musickitloaded', async () => {
console.log('MusicKit loaded.');
// Configure MusicKit with your developer token
await MusicKit.configure({
developerToken: 'MY_VALID_TOKEN', // <-- Replace with your valid token
app: {
name: 'MinimalTestApp',
build: '1.0.0'
}
});
const music = MusicKit.getInstance();
// 1) Authorization Flow
// Per the article: "User authorization is required before your app can access
// the user’s Apple Music data ... or for full playback of media."
document.getElementById('authorize-btn').addEventListener('click', async () => {
try {
console.log('Attempting to authorize...');
await music.authorize();
console.log('Authorization successful!');
} catch (error) {
console.error('Authorization failed:', error);
}
});
// 2) Playing a Preview
// "Without user authorization, or for users who do not have a valid Apple Music subscription,
// your app can still play previews of media from Apple Music."
document.getElementById('play-preview-btn').addEventListener('click', async () => {
try {
console.log('Attempting to play a preview...');
// Set a queue with a known track ID that supports previews.
// This ID is just an example; you can replace it with any track that has a preview.
await music.setQueue({ song: '1641309998' });
await music.player.play();
console.log('Playing preview (if available)...');
} catch (error) {
console.error('Error playing preview:', error);
}
});
// If you want to play the full length of a song, ensure the user is authorized
// with an active Apple Music subscription. Then do:
//
// await music.authorize();
// await music.play();
//
// per the article’s guidance.
});
</script>
</body>
</html>