Flutter音乐播放管理插件music_kit的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter音乐播放管理插件music_kit的使用

music_kit 是一个用于访问和播放Apple Music的Flutter插件。它支持Android和iOS平台。

平台支持

Android iOS MacOS Web Linux Windows
✔️ ✔️

使用方法

要在项目中使用这个插件,请在 pubspec.yaml 文件中添加 music_kit 作为依赖项。

额外步骤(针对Android)

  1. 在构建文件中添加JitPack仓库:
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
    
  2. 在使用MusicKit实例之前,手动调用 initialize(developerToken, musicUserToken: [userToken]) 方法。

示例代码

下面是一个完整的示例Demo,展示了如何初始化并使用 music_kit 插件来播放音乐:

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:music_kit/music_kit.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _musicKitPlugin = MusicKit();
  MusicAuthorizationStatus _status = MusicAuthorizationStatusNotDetermined();
  String? _developerToken = '';
  String _userToken = '';
  String _countryCode = '';

  MusicSubscription _musicSubsciption = const MusicSubscription();
  late StreamSubscription<MusicSubscription> _musicSubscriptionStreamSubscription;

  MusicPlayerState? _playerState;
  late StreamSubscription<MusicPlayerState> _playerStateStreamSubscription;

  MusicPlayerQueue? _playerQueue;
  late StreamSubscription<MusicPlayerQueue> _playerQueueStreamSubscription;

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();

    _musicSubscriptionStreamSubscription =
        _musicKitPlugin.onSubscriptionUpdated.listen((event) {
      setState(() {
        _musicSubsciption = event;
      });
    });

    _playerStateStreamSubscription =
        _musicKitPlugin.onMusicPlayerStateChanged.listen((event) {
      setState(() {
        _playerState = event;
      });
    });

    _playerQueueStreamSubscription =
        _musicKitPlugin.onPlayerQueueChanged.listen((event) {
      setState(() {
        _playerQueue = event;
      });
    });
  }

  [@override](/user/override)
  void dispose() {
    _musicSubscriptionStreamSubscription.cancel();
    _playerStateStreamSubscription.cancel();
    _playerQueueStreamSubscription.cancel();
    super.dispose();
  }

  Future<void> initPlatformState() async {
    final status = await _musicKitPlugin.authorizationStatus;

    switch (status) {
      case MusicAuthorizationStatusInitial():
      case MusicAuthorizationStatusDenied():
      case MusicAuthorizationStatusNotDetermined():
      case MusicAuthorizationStatusRestricted():
        return;
      case MusicAuthorizationStatusAuthorized():
        break;
    }

    final developerToken = await _musicKitPlugin.requestDeveloperToken();

    if (_musicSubsciption.canBecomeSubscriber == true) return;

    final userToken = await _musicKitPlugin.requestUserToken(developerToken);

    final countryCode = await _musicKitPlugin.currentCountryCode;

    if (!mounted) return;

    setState(() {
      _status = status;
      _developerToken = developerToken;
      _userToken = userToken;
      _countryCode = countryCode;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('DeveloperToken: $_developerToken\n', maxLines: 3),
              Text('UserToken: $_userToken\n', maxLines: 3),
              Text('Status: ${_status.toString()}\n'),
              Text('CountryCode: $_countryCode\n'),
              Text('Subscription: ${_musicSubsciption.toString()}\n'),
              Text('PlayerState: ${_playerState?.playbackStatus.toString()}'),
              Text('PlayerQueue: ${_playerQueue?.currentEntry?.title}'),
              TextButton(
                  onPressed: () async {
                    _musicKitPlugin.setShuffleMode(MusicPlayerShuffleMode.songs);
                    _musicKitPlugin.musicPlayerState.then((value) => debugPrint(value.shuffleMode.name));
                  },
                  child: const Text('Shuffle')),
              TextButton(
                  onPressed: () async {
                    final status = await _musicKitPlugin.requestAuthorizationStatus();
                    setState(() {
                      _status = status;
                    });
                  },
                  child: const Text('Request authorization')),
              TextButton(
                  onPressed: () async {
                    await _musicKitPlugin.setQueue(albumFolklore['type'], item: albumFolklore);
                    await _musicKitPlugin.play();
                  },
                  child: const Text('Play an Album'))
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter音乐播放管理插件music_kit的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter音乐播放管理插件music_kit的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用music_kit插件进行音乐播放管理的代码示例。music_kit是一个假设的音乐播放管理插件,用于演示目的,实际使用中你可能需要参考具体插件的文档。假设music_kit提供了基本的音乐播放功能,如播放、暂停、停止以及获取当前播放状态等。

首先,确保你已经在pubspec.yaml文件中添加了music_kit依赖:

dependencies:
  flutter:
    sdk: flutter
  music_kit: ^x.y.z  # 替换为实际版本号

然后运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中创建一个音乐播放管理文件,例如music_service.dart

import 'package:flutter/material.dart';
import 'package:music_kit/music_kit.dart';

class MusicService with ChangeNotifier {
  MusicKit _musicKit = MusicKit();

  MusicState get currentState => _musicKit.currentState;

  Future<void> playMusic(String musicUrl) async {
    await _musicKit.play(musicUrl);
    notifyListeners();
  }

  Future<void> pauseMusic() async {
    await _musicKit.pause();
    notifyListeners();
  }

  Future<void> stopMusic() async {
    await _musicKit.stop();
    notifyListeners();
  }

  Future<void> seekTo(Duration position) async {
    await _musicKit.seekTo(position);
    notifyListeners();
  }

  Duration get currentPosition => _musicKit.currentPosition;

  Duration get duration => _musicKit.duration;
}

enum MusicState { playing, paused, stopped, unknown }

在你的主应用文件中(例如main.dart),你可以使用Provider来管理音乐播放状态:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'music_service.dart';

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => MusicService()),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Music Player',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MusicPlayerScreen(),
    );
  }
}

class MusicPlayerScreen extends StatefulWidget {
  @override
  _MusicPlayerScreenState createState() => _MusicPlayerScreenState();
}

class _MusicPlayerScreenState extends State<MusicPlayerScreen> {
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final musicService = Provider.of<MusicService>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Music Player'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                labelText: 'Enter music URL',
              ),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () async {
                await musicService.playMusic(_controller.text);
              },
              child: Text('Play'),
            ),
            SizedBox(height: 8),
            ElevatedButton(
              onPressed: () async {
                await musicService.pauseMusic();
              },
              child: Text('Pause'),
            ),
            SizedBox(height: 8),
            ElevatedButton(
              onPressed: () async {
                await musicService.stopMusic();
              },
              child: Text('Stop'),
            ),
            SizedBox(height: 32),
            Text('Current State: ${musicService.currentState}'),
            SizedBox(height: 16),
            Text('Current Position: ${musicService.currentPosition.toString()}'),
            SizedBox(height: 16),
            Text('Duration: ${musicService.duration.toString()}'),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个MusicService类来管理音乐播放逻辑,并使用Provider来在UI组件中访问和监听音乐播放状态的变化。MusicPlayerScreen是一个简单的用户界面,允许用户输入音乐URL并控制播放、暂停和停止操作。

请注意,由于music_kit是一个假设的插件,实际使用时你需要参考具体插件的API文档来替换上述代码中的方法调用。

回到顶部