xref: /MusicFree/src/core/trackPlayer/index.ts (revision 119089394f8cb5fd7ad1b7ab1abe8a78644f4245)
15500cea7S猫头猫import produce from 'immer';
25500cea7S猫头猫import ReactNativeTrackPlayer, {
35500cea7S猫头猫    Event,
45500cea7S猫头猫    State,
55500cea7S猫头猫    Track,
65500cea7S猫头猫    TrackMetadataBase,
75500cea7S猫头猫    usePlaybackState,
85500cea7S猫头猫    useProgress,
95500cea7S猫头猫} from 'react-native-track-player';
105500cea7S猫头猫import shuffle from 'lodash.shuffle';
115500cea7S猫头猫import Config from '../config';
125500cea7S猫头猫import {
135500cea7S猫头猫    EDeviceEvents,
145500cea7S猫头猫    internalFakeSoundKey,
155500cea7S猫头猫    sortIndexSymbol,
165500cea7S猫头猫    timeStampSymbol,
175500cea7S猫头猫} from '@/constants/commonConst';
185500cea7S猫头猫import {GlobalState} from '@/utils/stateMapper';
195500cea7S猫头猫import delay from '@/utils/delay';
205500cea7S猫头猫import {
215500cea7S猫头猫    isSameMediaItem,
225500cea7S猫头猫    mergeProps,
235500cea7S猫头猫    sortByTimestampAndIndex,
245500cea7S猫头猫} from '@/utils/mediaItem';
255500cea7S猫头猫import Network from '../network';
265500cea7S猫头猫import LocalMusicSheet from '../localMusicSheet';
275500cea7S猫头猫import {SoundAsset} from '@/constants/assetsConst';
285500cea7S猫头猫import {getQualityOrder} from '@/utils/qualities';
295500cea7S猫头猫import musicHistory from '../musicHistory';
305500cea7S猫头猫import getUrlExt from '@/utils/getUrlExt';
315500cea7S猫头猫import {DeviceEventEmitter} from 'react-native';
325500cea7S猫头猫import LyricManager from '../lyricManager';
335500cea7S猫头猫import {MusicRepeatMode} from './common';
345500cea7S猫头猫import {
355500cea7S猫头猫    getMusicIndex,
365500cea7S猫头猫    getPlayList,
375500cea7S猫头猫    getPlayListMusicAt,
385500cea7S猫头猫    isInPlayList,
395500cea7S猫头猫    isPlayListEmpty,
405500cea7S猫头猫    setPlayList,
415500cea7S猫头猫    usePlayList,
425500cea7S猫头猫} from './internal/playList';
435500cea7S猫头猫import {createMediaIndexMap} from '@/utils/mediaIndexMap';
445500cea7S猫头猫import PluginManager from '../pluginManager';
455500cea7S猫头猫import {musicIsPaused} from '@/utils/trackUtils';
46f511aee9S猫头猫import Toast from '@/utils/toast';
4762e73a5eS猫头猫import {trace} from '@/utils/log';
486e000b99S猫头猫import PersistStatus from '../persistStatus';
495500cea7S猫头猫
505500cea7S猫头猫/** 当前播放 */
515500cea7S猫头猫const currentMusicStore = new GlobalState<IMusic.IMusicItem | null>(null);
525500cea7S猫头猫
535500cea7S猫头猫/** 播放模式 */
545500cea7S猫头猫const repeatModeStore = new GlobalState<MusicRepeatMode>(MusicRepeatMode.QUEUE);
555500cea7S猫头猫
565500cea7S猫头猫/** 音质 */
575500cea7S猫头猫const qualityStore = new GlobalState<IMusic.IQualityKey>('standard');
585500cea7S猫头猫
595500cea7S猫头猫let currentIndex = -1;
605500cea7S猫头猫
615500cea7S猫头猫// TODO: 下个版本最大限制调大一些
625500cea7S猫头猫const maxMusicQueueLength = 1500; // 当前播放最大限制
635500cea7S猫头猫const halfMaxMusicQueueLength = Math.floor(maxMusicQueueLength / 2);
645500cea7S猫头猫const shrinkPlayListToSize = (
655500cea7S猫头猫    queue: IMusic.IMusicItem[],
665500cea7S猫头猫    targetIndex = currentIndex,
675500cea7S猫头猫) => {
685500cea7S猫头猫    // 播放列表上限,太多无法缓存状态
695500cea7S猫头猫    if (queue.length > maxMusicQueueLength) {
705500cea7S猫头猫        if (targetIndex < halfMaxMusicQueueLength) {
715500cea7S猫头猫            queue = queue.slice(0, maxMusicQueueLength);
725500cea7S猫头猫        } else {
735500cea7S猫头猫            const right = Math.min(
745500cea7S猫头猫                queue.length,
755500cea7S猫头猫                targetIndex + halfMaxMusicQueueLength,
765500cea7S猫头猫            );
775500cea7S猫头猫            const left = Math.max(0, right - maxMusicQueueLength);
785500cea7S猫头猫            queue = queue.slice(left, right);
795500cea7S猫头猫        }
805500cea7S猫头猫    }
815500cea7S猫头猫    return queue;
825500cea7S猫头猫};
835500cea7S猫头猫
847aed04d4S猫头猫let hasSetupListener = false;
857aed04d4S猫头猫
866e000b99S猫头猫// TODO: 删除
876e000b99S猫头猫function migrate() {
886e000b99S猫头猫    const config = Config.get('status.music');
896e000b99S猫头猫    if (!config) {
906e000b99S猫头猫        return;
916e000b99S猫头猫    }
925500cea7S猫头猫    const {rate, repeatMode, musicQueue, progress, track} = config;
936e000b99S猫头猫    PersistStatus.set('music.rate', rate);
946e000b99S猫头猫    PersistStatus.set('music.repeatMode', repeatMode);
956e000b99S猫头猫    PersistStatus.set('music.playList', musicQueue);
966e000b99S猫头猫    PersistStatus.set('music.progress', progress);
976e000b99S猫头猫    PersistStatus.set('music.musicItem', track);
986e000b99S猫头猫    Config.set('status.music', undefined);
996e000b99S猫头猫}
1006e000b99S猫头猫
1016e000b99S猫头猫async function setupTrackPlayer() {
1026e000b99S猫头猫    migrate();
1036e000b99S猫头猫
1046e000b99S猫头猫    const rate = PersistStatus.get('music.rate');
1056e000b99S猫头猫    const musicQueue = PersistStatus.get('music.playList');
1066e000b99S猫头猫    const repeatMode = PersistStatus.get('music.repeatMode');
1076e000b99S猫头猫    const progress = PersistStatus.get('music.progress');
1086e000b99S猫头猫    const track = PersistStatus.get('music.musicItem');
1096e000b99S猫头猫    const quality =
1106e000b99S猫头猫        PersistStatus.get('music.quality') ||
1116e000b99S猫头猫        Config.get('setting.basic.defaultPlayQuality') ||
1126e000b99S猫头猫        'standard';
1135500cea7S猫头猫
1145500cea7S猫头猫    // 状态恢复
1155500cea7S猫头猫    if (rate) {
1165500cea7S猫头猫        await ReactNativeTrackPlayer.setRate(+rate / 100);
1175500cea7S猫头猫    }
1185500cea7S猫头猫
1195500cea7S猫头猫    if (musicQueue && Array.isArray(musicQueue)) {
1205500cea7S猫头猫        addAll(musicQueue, undefined, repeatMode === MusicRepeatMode.SHUFFLE);
1215500cea7S猫头猫    }
1225500cea7S猫头猫
1235500cea7S猫头猫    if (track && isInPlayList(track)) {
1245500cea7S猫头猫        const newSource = await PluginManager.getByMedia(
1255500cea7S猫头猫            track,
1266e000b99S猫头猫        )?.methods.getMediaSource(track, quality, 0);
1275500cea7S猫头猫        // 重新初始化 获取最新的链接
1285500cea7S猫头猫        track.url = newSource?.url || track.url;
1295500cea7S猫头猫        track.headers = newSource?.headers || track.headers;
1308b9904b3S猫头猫        if (!Config.get('setting.basic.autoPlayWhenAppStart')) {
1318b9904b3S猫头猫            track.isInit = true;
1328b9904b3S猫头猫        }
1330dd58d38S猫头猫
1345500cea7S猫头猫        await setTrackSource(track as Track, false);
1355500cea7S猫头猫        setCurrentMusic(track);
1365500cea7S猫头猫
1376e000b99S猫头猫        if (progress) {
1386e000b99S猫头猫            await ReactNativeTrackPlayer.seekTo(progress);
1395500cea7S猫头猫        }
1405500cea7S猫头猫    }
1415500cea7S猫头猫
1427aed04d4S猫头猫    if (!hasSetupListener) {
1435500cea7S猫头猫        ReactNativeTrackPlayer.addEventListener(
1445500cea7S猫头猫            Event.PlaybackActiveTrackChanged,
1455500cea7S猫头猫            async evt => {
1465500cea7S猫头猫                if (
1475500cea7S猫头猫                    evt.index === 1 &&
1485500cea7S猫头猫                    evt.lastIndex === 0 &&
1495500cea7S猫头猫                    evt.track?.$ === internalFakeSoundKey
1505500cea7S猫头猫                ) {
15162e73a5eS猫头猫                    trace('队列末尾,播放下一首');
1525500cea7S猫头猫                    if (repeatModeStore.getValue() === MusicRepeatMode.SINGLE) {
1535500cea7S猫头猫                        await play(null, true);
1545500cea7S猫头猫                    } else {
1555500cea7S猫头猫                        // 当前生效的歌曲是下一曲的标记
1566f57784cS猫头猫                        await skipToNext();
1575500cea7S猫头猫                    }
1585500cea7S猫头猫                }
1595500cea7S猫头猫            },
1605500cea7S猫头猫        );
1615500cea7S猫头猫
1627aed04d4S猫头猫        ReactNativeTrackPlayer.addEventListener(
1637aed04d4S猫头猫            Event.PlaybackError,
16462e73a5eS猫头猫            async e => {
16562e73a5eS猫头猫                // WARNING: 不稳定,报错的时候有可能track已经变到下一首歌去了
1668b9904b3S猫头猫                const currentTrack =
1678b9904b3S猫头猫                    await ReactNativeTrackPlayer.getActiveTrack();
1688b9904b3S猫头猫                if (currentTrack?.isInit) {
1698b9904b3S猫头猫                    // HACK: 避免初始失败的情况
1708b9904b3S猫头猫                    ReactNativeTrackPlayer.updateMetadataForTrack(0, {
1718b9904b3S猫头猫                        ...currentTrack,
1728b9904b3S猫头猫                        // @ts-ignore
1738b9904b3S猫头猫                        isInit: undefined,
1748b9904b3S猫头猫                    });
1758b9904b3S猫头猫                    return;
1768b9904b3S猫头猫                }
1778b9904b3S猫头猫
1787aed04d4S猫头猫                if (
17962e73a5eS猫头猫                    (await ReactNativeTrackPlayer.getActiveTrackIndex()) ===
18062e73a5eS猫头猫                        0 &&
18162e73a5eS猫头猫                    e.message &&
18262e73a5eS猫头猫                    e.message !== 'android-io-file-not-found'
1837aed04d4S猫头猫                ) {
18462e73a5eS猫头猫                    trace('播放出错', {
18562e73a5eS猫头猫                        message: e.message,
18662e73a5eS猫头猫                        code: e.code,
18762e73a5eS猫头猫                    });
1888b9904b3S猫头猫
1895500cea7S猫头猫                    failToPlay();
1905500cea7S猫头猫                }
1917aed04d4S猫头猫            },
1927aed04d4S猫头猫        );
1937aed04d4S猫头猫
1947aed04d4S猫头猫        hasSetupListener = true;
1957aed04d4S猫头猫    }
1965500cea7S猫头猫}
1975500cea7S猫头猫
1985500cea7S猫头猫/**
1995500cea7S猫头猫 * 获取自动播放的下一个track
2005500cea7S猫头猫 */
2015500cea7S猫头猫const getFakeNextTrack = () => {
2025500cea7S猫头猫    let track: Track | undefined;
2035500cea7S猫头猫    const repeatMode = repeatModeStore.getValue();
2045500cea7S猫头猫    if (repeatMode === MusicRepeatMode.SINGLE) {
2055500cea7S猫头猫        // 单曲循环
2065500cea7S猫头猫        track = getPlayListMusicAt(currentIndex) as Track;
2075500cea7S猫头猫    } else {
2085500cea7S猫头猫        // 下一曲
2095500cea7S猫头猫        track = getPlayListMusicAt(currentIndex + 1) as Track;
2105500cea7S猫头猫    }
2115500cea7S猫头猫
2125500cea7S猫头猫    if (track) {
2135500cea7S猫头猫        return produce(track, _ => {
2145500cea7S猫头猫            _.url = SoundAsset.fakeAudio;
2155500cea7S猫头猫            _.$ = internalFakeSoundKey;
2165500cea7S猫头猫        });
2175500cea7S猫头猫    } else {
2185500cea7S猫头猫        // 只有列表长度为0时才会出现的特殊情况
2195500cea7S猫头猫        return {url: SoundAsset.fakeAudio, $: internalFakeSoundKey} as Track;
2205500cea7S猫头猫    }
2215500cea7S猫头猫};
2225500cea7S猫头猫
2235500cea7S猫头猫/** 播放失败时的情况 */
2246f57784cS猫头猫async function failToPlay() {
2255500cea7S猫头猫    // 如果自动跳转下一曲, 500s后自动跳转
2265500cea7S猫头猫    if (!Config.get('setting.basic.autoStopWhenError')) {
2275500cea7S猫头猫        await ReactNativeTrackPlayer.reset();
2285500cea7S猫头猫        await delay(500);
2296f57784cS猫头猫        await skipToNext();
2305500cea7S猫头猫    }
2315500cea7S猫头猫}
2325500cea7S猫头猫
2335500cea7S猫头猫// 播放模式相关
2345500cea7S猫头猫const _toggleRepeatMapping = {
2355500cea7S猫头猫    [MusicRepeatMode.SHUFFLE]: MusicRepeatMode.SINGLE,
2365500cea7S猫头猫    [MusicRepeatMode.SINGLE]: MusicRepeatMode.QUEUE,
2375500cea7S猫头猫    [MusicRepeatMode.QUEUE]: MusicRepeatMode.SHUFFLE,
2385500cea7S猫头猫};
2395500cea7S猫头猫/** 切换下一个模式 */
2405500cea7S猫头猫const toggleRepeatMode = () => {
2415500cea7S猫头猫    setRepeatMode(_toggleRepeatMapping[repeatModeStore.getValue()]);
2425500cea7S猫头猫};
2435500cea7S猫头猫
2445500cea7S猫头猫/**
2455500cea7S猫头猫 * 添加到播放列表
2465500cea7S猫头猫 * @param musicItems 目标歌曲
2475500cea7S猫头猫 * @param beforeIndex 在第x首歌曲前添加
2485500cea7S猫头猫 * @param shouldShuffle 随机排序
2495500cea7S猫头猫 */
2505500cea7S猫头猫const addAll = (
2515500cea7S猫头猫    musicItems: Array<IMusic.IMusicItem> = [],
2525500cea7S猫头猫    beforeIndex?: number,
2535500cea7S猫头猫    shouldShuffle?: boolean,
2545500cea7S猫头猫) => {
2555500cea7S猫头猫    const now = Date.now();
2565500cea7S猫头猫    let newPlayList: IMusic.IMusicItem[] = [];
2575500cea7S猫头猫    let currentPlayList = getPlayList();
2585500cea7S猫头猫    const _musicItems = musicItems.map((item, index) =>
2595500cea7S猫头猫        produce(item, draft => {
2605500cea7S猫头猫            draft[timeStampSymbol] = now;
2615500cea7S猫头猫            draft[sortIndexSymbol] = index;
2625500cea7S猫头猫        }),
2635500cea7S猫头猫    );
2645500cea7S猫头猫    if (beforeIndex === undefined || beforeIndex < 0) {
2655500cea7S猫头猫        // 1.1. 添加到歌单末尾,并过滤掉已有的歌曲
2665500cea7S猫头猫        newPlayList = currentPlayList.concat(
2675500cea7S猫头猫            _musicItems.filter(item => !isInPlayList(item)),
2685500cea7S猫头猫        );
2695500cea7S猫头猫    } else {
2705500cea7S猫头猫        // 1.2. 新的播放列表,插入
2715500cea7S猫头猫        const indexMap = createMediaIndexMap(_musicItems);
2725500cea7S猫头猫        const beforeDraft = currentPlayList
2735500cea7S猫头猫            .slice(0, beforeIndex)
2745500cea7S猫头猫            .filter(item => !indexMap.has(item));
2755500cea7S猫头猫        const afterDraft = currentPlayList
2765500cea7S猫头猫            .slice(beforeIndex)
2775500cea7S猫头猫            .filter(item => !indexMap.has(item));
2785500cea7S猫头猫
2795500cea7S猫头猫        newPlayList = [...beforeDraft, ..._musicItems, ...afterDraft];
2805500cea7S猫头猫    }
28115900d05S猫头猫
2825500cea7S猫头猫    // 如果太长了
2835500cea7S猫头猫    if (newPlayList.length > maxMusicQueueLength) {
2845500cea7S猫头猫        newPlayList = shrinkPlayListToSize(
2855500cea7S猫头猫            newPlayList,
2865500cea7S猫头猫            beforeIndex ?? newPlayList.length - 1,
2875500cea7S猫头猫        );
2885500cea7S猫头猫    }
2895500cea7S猫头猫
2905500cea7S猫头猫    // 2. 如果需要随机
2915500cea7S猫头猫    if (shouldShuffle) {
2925500cea7S猫头猫        newPlayList = shuffle(newPlayList);
2935500cea7S猫头猫    }
2945500cea7S猫头猫    // 3. 设置播放列表
2955500cea7S猫头猫    setPlayList(newPlayList);
2965500cea7S猫头猫    const currentMusicItem = currentMusicStore.getValue();
2975500cea7S猫头猫
2985500cea7S猫头猫    // 4. 重置下标
2995500cea7S猫头猫    if (currentMusicItem) {
3005500cea7S猫头猫        currentIndex = getMusicIndex(currentMusicItem);
3015500cea7S猫头猫    }
3025500cea7S猫头猫
3035500cea7S猫头猫    // TODO: 更新播放队列信息
3045500cea7S猫头猫    // 5. 存储更新的播放列表信息
3055500cea7S猫头猫};
3065500cea7S猫头猫
3075500cea7S猫头猫/** 追加到队尾 */
3085500cea7S猫头猫const add = (
3095500cea7S猫头猫    musicItem: IMusic.IMusicItem | IMusic.IMusicItem[],
3105500cea7S猫头猫    beforeIndex?: number,
3115500cea7S猫头猫) => {
3125500cea7S猫头猫    addAll(Array.isArray(musicItem) ? musicItem : [musicItem], beforeIndex);
3135500cea7S猫头猫};
3145500cea7S猫头猫
3155500cea7S猫头猫/**
3165500cea7S猫头猫 * 下一首播放
3175500cea7S猫头猫 * @param musicItem
3185500cea7S猫头猫 */
3195500cea7S猫头猫const addNext = (musicItem: IMusic.IMusicItem | IMusic.IMusicItem[]) => {
3205500cea7S猫头猫    const shouldPlay = isPlayListEmpty();
3215500cea7S猫头猫    add(musicItem, currentIndex + 1);
3225500cea7S猫头猫    if (shouldPlay) {
3235500cea7S猫头猫        play(Array.isArray(musicItem) ? musicItem[0] : musicItem);
3245500cea7S猫头猫    }
3255500cea7S猫头猫};
3265500cea7S猫头猫
3275500cea7S猫头猫const isCurrentMusic = (musicItem: IMusic.IMusicItem) => {
3285500cea7S猫头猫    return isSameMediaItem(musicItem, currentMusicStore.getValue()) ?? false;
3295500cea7S猫头猫};
3305500cea7S猫头猫
3315500cea7S猫头猫const remove = async (musicItem: IMusic.IMusicItem) => {
3325500cea7S猫头猫    const playList = getPlayList();
3335500cea7S猫头猫    let newPlayList: IMusic.IMusicItem[] = [];
3345500cea7S猫头猫    let currentMusic: IMusic.IMusicItem | null = currentMusicStore.getValue();
3355500cea7S猫头猫    const targetIndex = getMusicIndex(musicItem);
3365500cea7S猫头猫    let shouldPlayCurrent: boolean | null = null;
3375500cea7S猫头猫    if (targetIndex === -1) {
3385500cea7S猫头猫        // 1. 这种情况应该是出错了
3395500cea7S猫头猫        return;
3405500cea7S猫头猫    }
3415500cea7S猫头猫    // 2. 移除的是当前项
3425500cea7S猫头猫    if (currentIndex === targetIndex) {
3435500cea7S猫头猫        // 2.1 停止播放,移除当前项
3445500cea7S猫头猫        newPlayList = produce(playList, draft => {
3455500cea7S猫头猫            draft.splice(targetIndex, 1);
3465500cea7S猫头猫        });
3475500cea7S猫头猫        // 2.2 设置新的播放列表,并更新当前音乐
3485500cea7S猫头猫        if (newPlayList.length === 0) {
3495500cea7S猫头猫            currentMusic = null;
3505500cea7S猫头猫            shouldPlayCurrent = false;
3515500cea7S猫头猫        } else {
3525500cea7S猫头猫            currentMusic = newPlayList[currentIndex % newPlayList.length];
3535500cea7S猫头猫            try {
3545500cea7S猫头猫                const state = (await ReactNativeTrackPlayer.getPlaybackState())
3555500cea7S猫头猫                    .state;
3565500cea7S猫头猫                if (musicIsPaused(state)) {
3575500cea7S猫头猫                    shouldPlayCurrent = false;
3585500cea7S猫头猫                } else {
3595500cea7S猫头猫                    shouldPlayCurrent = true;
3605500cea7S猫头猫                }
3615500cea7S猫头猫            } catch {
3625500cea7S猫头猫                shouldPlayCurrent = false;
3635500cea7S猫头猫            }
3645500cea7S猫头猫        }
3655500cea7S猫头猫    } else {
3665500cea7S猫头猫        // 3. 删除
3675500cea7S猫头猫        newPlayList = produce(playList, draft => {
3685500cea7S猫头猫            draft.splice(targetIndex, 1);
3695500cea7S猫头猫        });
3705500cea7S猫头猫    }
3715500cea7S猫头猫
3725500cea7S猫头猫    setPlayList(newPlayList);
3735500cea7S猫头猫    setCurrentMusic(currentMusic);
3745500cea7S猫头猫    if (shouldPlayCurrent === true) {
3755500cea7S猫头猫        await play(currentMusic, true);
3765500cea7S猫头猫    } else if (shouldPlayCurrent === false) {
3775500cea7S猫头猫        await ReactNativeTrackPlayer.reset();
3785500cea7S猫头猫    }
3795500cea7S猫头猫};
3805500cea7S猫头猫
3815500cea7S猫头猫/**
3825500cea7S猫头猫 * 设置播放模式
3835500cea7S猫头猫 * @param mode 播放模式
3845500cea7S猫头猫 */
3855500cea7S猫头猫const setRepeatMode = (mode: MusicRepeatMode) => {
3865500cea7S猫头猫    const playList = getPlayList();
3875500cea7S猫头猫    let newPlayList;
3885500cea7S猫头猫    if (mode === MusicRepeatMode.SHUFFLE) {
3895500cea7S猫头猫        newPlayList = shuffle(playList);
3905500cea7S猫头猫    } else {
3915500cea7S猫头猫        newPlayList = produce(playList, draft => {
3925500cea7S猫头猫            return sortByTimestampAndIndex(draft);
3935500cea7S猫头猫        });
3945500cea7S猫头猫    }
3955500cea7S猫头猫
3965500cea7S猫头猫    setPlayList(newPlayList);
3975500cea7S猫头猫    const currentMusicItem = currentMusicStore.getValue();
3985500cea7S猫头猫    currentIndex = getMusicIndex(currentMusicItem);
3995500cea7S猫头猫    repeatModeStore.setValue(mode);
4005500cea7S猫头猫    // 更新下一首歌的信息
4015500cea7S猫头猫    ReactNativeTrackPlayer.updateMetadataForTrack(1, getFakeNextTrack());
4025500cea7S猫头猫    // 记录
4036e000b99S猫头猫    PersistStatus.set('music.repeatMode', mode);
4045500cea7S猫头猫};
4055500cea7S猫头猫
4065500cea7S猫头猫/** 清空播放列表 */
4075500cea7S猫头猫const clear = async () => {
4085500cea7S猫头猫    setPlayList([]);
4095500cea7S猫头猫    setCurrentMusic(null);
4105500cea7S猫头猫
4115500cea7S猫头猫    await ReactNativeTrackPlayer.reset();
4126e000b99S猫头猫    PersistStatus.set('music.musicItem', undefined);
4136e000b99S猫头猫    PersistStatus.set('music.progress', 0);
4145500cea7S猫头猫};
4155500cea7S猫头猫
4165500cea7S猫头猫/** 暂停 */
4175500cea7S猫头猫const pause = async () => {
4185500cea7S猫头猫    await ReactNativeTrackPlayer.pause();
4195500cea7S猫头猫};
4205500cea7S猫头猫
4218b9904b3S猫头猫/** 设置音源 */
4228b9904b3S猫头猫const setTrackSource = async (track: Track, autoPlay = true) => {
423*11908939S猫头猫    if (!track.artwork?.trim()?.length) {
424*11908939S猫头猫        track.artwork = undefined;
425*11908939S猫头猫    }
4268b9904b3S猫头猫    await ReactNativeTrackPlayer.setQueue([track, getFakeNextTrack()]);
4278b9904b3S猫头猫    PersistStatus.set('music.musicItem', track as IMusic.IMusicItem);
4288b9904b3S猫头猫    PersistStatus.set('music.progress', 0);
4298b9904b3S猫头猫    if (autoPlay) {
4308b9904b3S猫头猫        await ReactNativeTrackPlayer.play();
4318b9904b3S猫头猫    }
4328b9904b3S猫头猫};
4338b9904b3S猫头猫
4345500cea7S猫头猫const setCurrentMusic = (musicItem?: IMusic.IMusicItem | null) => {
4355500cea7S猫头猫    if (!musicItem) {
4365500cea7S猫头猫        currentIndex = -1;
437f511aee9S猫头猫        currentMusicStore.setValue(null);
4386e000b99S猫头猫        PersistStatus.set('music.musicItem', undefined);
4396e000b99S猫头猫        PersistStatus.set('music.progress', 0);
4406e000b99S猫头猫        return;
4415500cea7S猫头猫    }
4425500cea7S猫头猫    currentIndex = getMusicIndex(musicItem);
4436e000b99S猫头猫    currentMusicStore.setValue(musicItem);
4445500cea7S猫头猫};
4455500cea7S猫头猫
4466e000b99S猫头猫const setQuality = (quality: IMusic.IQualityKey) => {
4476e000b99S猫头猫    qualityStore.setValue(quality);
4486e000b99S猫头猫    PersistStatus.set('music.quality', quality);
4496e000b99S猫头猫};
4505500cea7S猫头猫/**
4515500cea7S猫头猫 * 播放
4525500cea7S猫头猫 *
4535500cea7S猫头猫 * 当musicItem 为空时,代表暂停/播放
4545500cea7S猫头猫 *
4555500cea7S猫头猫 * @param musicItem
4565500cea7S猫头猫 * @param forcePlay
4575500cea7S猫头猫 * @returns
4585500cea7S猫头猫 */
4595500cea7S猫头猫const play = async (
4605500cea7S猫头猫    musicItem?: IMusic.IMusicItem | null,
4615500cea7S猫头猫    forcePlay?: boolean,
4625500cea7S猫头猫) => {
4635500cea7S猫头猫    try {
4645500cea7S猫头猫        if (!musicItem) {
4655500cea7S猫头猫            musicItem = currentMusicStore.getValue();
4665500cea7S猫头猫        }
4675500cea7S猫头猫        if (!musicItem) {
4685500cea7S猫头猫            throw new Error(PlayFailReason.PLAY_LIST_IS_EMPTY);
4695500cea7S猫头猫        }
4705500cea7S猫头猫        // 1. 移动网络禁止播放
4715500cea7S猫头猫        if (
4725500cea7S猫头猫            Network.isCellular() &&
4735500cea7S猫头猫            !Config.get('setting.basic.useCelluarNetworkPlay') &&
4745500cea7S猫头猫            !LocalMusicSheet.isLocalMusic(musicItem)
4755500cea7S猫头猫        ) {
4765500cea7S猫头猫            await ReactNativeTrackPlayer.reset();
4775500cea7S猫头猫            throw new Error(PlayFailReason.FORBID_CELLUAR_NETWORK_PLAY);
4785500cea7S猫头猫        }
4795500cea7S猫头猫
4805500cea7S猫头猫        // 2. 如果是当前正在播放的音频
4815500cea7S猫头猫        if (isCurrentMusic(musicItem)) {
4825500cea7S猫头猫            const currentTrack = await ReactNativeTrackPlayer.getTrack(0);
4835500cea7S猫头猫            // 2.1 如果当前有源
4845500cea7S猫头猫            if (
4855500cea7S猫头猫                currentTrack?.url &&
4865500cea7S猫头猫                isSameMediaItem(musicItem, currentTrack as IMusic.IMusicItem)
4875500cea7S猫头猫            ) {
4885500cea7S猫头猫                const currentActiveIndex =
4895500cea7S猫头猫                    await ReactNativeTrackPlayer.getActiveTrackIndex();
4905500cea7S猫头猫                if (currentActiveIndex !== 0) {
4915500cea7S猫头猫                    await ReactNativeTrackPlayer.skip(0);
4925500cea7S猫头猫                }
4935500cea7S猫头猫                if (forcePlay) {
4945500cea7S猫头猫                    // 2.1.1 强制重新开始
4955500cea7S猫头猫                    await ReactNativeTrackPlayer.seekTo(0);
4966f57784cS猫头猫                }
49766e1d5fcS猫头猫                const currentState = (
49866e1d5fcS猫头猫                    await ReactNativeTrackPlayer.getPlaybackState()
49966e1d5fcS猫头猫                ).state;
50066e1d5fcS猫头猫                if (currentState === State.Stopped) {
50166e1d5fcS猫头猫                    await setTrackSource(currentTrack);
50266e1d5fcS猫头猫                }
50366e1d5fcS猫头猫                if (currentState !== State.Playing) {
5045500cea7S猫头猫                    // 2.1.2 恢复播放
5055500cea7S猫头猫                    await ReactNativeTrackPlayer.play();
5065500cea7S猫头猫                }
5075500cea7S猫头猫                // 这种情况下,播放队列和当前歌曲都不需要变化
5085500cea7S猫头猫                return;
5095500cea7S猫头猫            }
5105500cea7S猫头猫            // 2.2 其他情况:重新获取源
5115500cea7S猫头猫        }
5125500cea7S猫头猫
5135500cea7S猫头猫        // 3. 如果没有在播放列表中,添加到队尾;同时更新列表状态
5145500cea7S猫头猫        const inPlayList = isInPlayList(musicItem);
5155500cea7S猫头猫        if (!inPlayList) {
5165500cea7S猫头猫            add(musicItem);
5175500cea7S猫头猫        }
5185500cea7S猫头猫
5195500cea7S猫头猫        // 4. 更新列表状态和当前音乐
5205500cea7S猫头猫        setCurrentMusic(musicItem);
5219cfce1b6S猫头猫        await ReactNativeTrackPlayer.reset();
5229cfce1b6S猫头猫
5239cfce1b6S猫头猫        // 4.1 刷新歌词信息
5249cfce1b6S猫头猫        if (
5259cfce1b6S猫头猫            !isSameMediaItem(
5269cfce1b6S猫头猫                LyricManager.getLyricState()?.lyricParser?.getCurrentMusicItem?.(),
5279cfce1b6S猫头猫                musicItem,
5289cfce1b6S猫头猫            )
5299cfce1b6S猫头猫        ) {
5309cfce1b6S猫头猫            DeviceEventEmitter.emit(EDeviceEvents.REFRESH_LYRIC, true);
5319cfce1b6S猫头猫        }
5325500cea7S猫头猫
5335500cea7S猫头猫        // 5. 获取音源
5345500cea7S猫头猫        let track: IMusic.IMusicItem;
5355500cea7S猫头猫
5365500cea7S猫头猫        // 5.1 通过插件获取音源
5375500cea7S猫头猫        const plugin = PluginManager.getByName(musicItem.platform);
5385500cea7S猫头猫        // 5.2 获取音质排序
5395500cea7S猫头猫        const qualityOrder = getQualityOrder(
5405500cea7S猫头猫            Config.get('setting.basic.defaultPlayQuality') ?? 'standard',
5415500cea7S猫头猫            Config.get('setting.basic.playQualityOrder') ?? 'asc',
5425500cea7S猫头猫        );
5435500cea7S猫头猫        // 5.3 插件返回音源
5445500cea7S猫头猫        let source: IPlugin.IMediaSourceResult | null = null;
5455500cea7S猫头猫        for (let quality of qualityOrder) {
5465500cea7S猫头猫            if (isCurrentMusic(musicItem)) {
5475500cea7S猫头猫                source =
5485500cea7S猫头猫                    (await plugin?.methods?.getMediaSource(
5495500cea7S猫头猫                        musicItem,
5505500cea7S猫头猫                        quality,
5515500cea7S猫头猫                    )) ?? null;
5525500cea7S猫头猫                // 5.3.1 获取到真实源
5535500cea7S猫头猫                if (source) {
5546e000b99S猫头猫                    setQuality(quality);
5556e000b99S猫头猫
5565500cea7S猫头猫                    break;
5575500cea7S猫头猫                }
5585500cea7S猫头猫            } else {
5595500cea7S猫头猫                // 5.3.2 已经切换到其他歌曲了,
5605500cea7S猫头猫                return;
5615500cea7S猫头猫            }
5625500cea7S猫头猫        }
5635500cea7S猫头猫
5645500cea7S猫头猫        if (!isCurrentMusic(musicItem)) {
5655500cea7S猫头猫            return;
5665500cea7S猫头猫        }
5675500cea7S猫头猫
5685500cea7S猫头猫        if (!source) {
56943eb30bfS猫头猫            // 如果有source
57043eb30bfS猫头猫            if (musicItem.source) {
57143eb30bfS猫头猫                for (let quality of qualityOrder) {
57243eb30bfS猫头猫                    if (musicItem.source[quality]?.url) {
57343eb30bfS猫头猫                        source = musicItem.source[quality]!;
5746e000b99S猫头猫                        setQuality(quality);
5756e000b99S猫头猫
57643eb30bfS猫头猫                        break;
5775500cea7S猫头猫                    }
57843eb30bfS猫头猫                }
57943eb30bfS猫头猫            }
58043eb30bfS猫头猫
58143eb30bfS猫头猫            // 5.4 没有返回源
58243eb30bfS猫头猫            if (!source && !musicItem.url) {
58343eb30bfS猫头猫                throw new Error(PlayFailReason.INVALID_SOURCE);
58443eb30bfS猫头猫            } else {
5855500cea7S猫头猫                source = {
5865500cea7S猫头猫                    url: musicItem.url,
5875500cea7S猫头猫                };
5886e000b99S猫头猫                setQuality('standard');
5895500cea7S猫头猫            }
59043eb30bfS猫头猫        }
5915500cea7S猫头猫
5925500cea7S猫头猫        // 6. 特殊类型源
5935500cea7S猫头猫        if (getUrlExt(source.url) === '.m3u8') {
5945500cea7S猫头猫            // @ts-ignore
5955500cea7S猫头猫            source.type = 'hls';
5965500cea7S猫头猫        }
5975500cea7S猫头猫        // 7. 合并结果
5985500cea7S猫头猫        track = mergeProps(musicItem, source) as IMusic.IMusicItem;
5995500cea7S猫头猫
6005500cea7S猫头猫        // 8. 新增历史记录
6015500cea7S猫头猫        musicHistory.addMusic(musicItem);
6025500cea7S猫头猫
60362e73a5eS猫头猫        trace('获取音源成功', track);
604*11908939S猫头猫        console.log('SSS', source, track);
6055500cea7S猫头猫        // 9. 设置音源
6065500cea7S猫头猫        await setTrackSource(track as Track);
607*11908939S猫头猫        console.log('DDD', source, track);
6085500cea7S猫头猫
6095500cea7S猫头猫        // 10. 获取补充信息
6105500cea7S猫头猫        let info: Partial<IMusic.IMusicItem> | null = null;
6115500cea7S猫头猫        try {
6125500cea7S猫头猫            info = (await plugin?.methods?.getMusicInfo?.(musicItem)) ?? null;
6135500cea7S猫头猫        } catch {}
6145500cea7S猫头猫
6155500cea7S猫头猫        // 11. 设置补充信息
6165500cea7S猫头猫        if (info && isCurrentMusic(musicItem)) {
6175500cea7S猫头猫            const mergedTrack = mergeProps(track, info);
6185500cea7S猫头猫            currentMusicStore.setValue(mergedTrack as IMusic.IMusicItem);
6195500cea7S猫头猫            await ReactNativeTrackPlayer.updateMetadataForTrack(
6205500cea7S猫头猫                0,
6215500cea7S猫头猫                mergedTrack as TrackMetadataBase,
6225500cea7S猫头猫            );
6235500cea7S猫头猫        }
6245500cea7S猫头猫    } catch (e: any) {
6255500cea7S猫头猫        const message = e?.message;
626*11908939S猫头猫        console.log(message, 'MMM', e);
6275500cea7S猫头猫        if (
6285500cea7S猫头猫            message === 'The player is not initialized. Call setupPlayer first.'
6295500cea7S猫头猫        ) {
6305500cea7S猫头猫            await ReactNativeTrackPlayer.setupPlayer();
6315500cea7S猫头猫            play(musicItem, forcePlay);
6325500cea7S猫头猫        } else if (message === PlayFailReason.FORBID_CELLUAR_NETWORK_PLAY) {
633f511aee9S猫头猫            Toast.warn(
634f511aee9S猫头猫                '当前禁止移动网络播放音乐,如需播放请去侧边栏-基本设置中修改',
635f511aee9S猫头猫            );
6365500cea7S猫头猫        } else if (message === PlayFailReason.INVALID_SOURCE) {
63762e73a5eS猫头猫            trace('音源为空,播放失败');
6386f57784cS猫头猫            await failToPlay();
6395500cea7S猫头猫        } else if (message === PlayFailReason.PLAY_LIST_IS_EMPTY) {
6405500cea7S猫头猫            // 队列是空的,不应该出现这种情况
6415500cea7S猫头猫        }
6425500cea7S猫头猫    }
6435500cea7S猫头猫};
6445500cea7S猫头猫
6455500cea7S猫头猫/**
6465500cea7S猫头猫 * 播放音乐,同时替换播放队列
6475500cea7S猫头猫 * @param musicItem 音乐
6485500cea7S猫头猫 * @param newPlayList 替代列表
6495500cea7S猫头猫 */
6505500cea7S猫头猫const playWithReplacePlayList = async (
6515500cea7S猫头猫    musicItem: IMusic.IMusicItem,
6525500cea7S猫头猫    newPlayList: IMusic.IMusicItem[],
6535500cea7S猫头猫) => {
6545500cea7S猫头猫    if (newPlayList.length !== 0) {
6555500cea7S猫头猫        const now = Date.now();
6565500cea7S猫头猫        if (newPlayList.length > maxMusicQueueLength) {
6575500cea7S猫头猫            newPlayList = shrinkPlayListToSize(
6585500cea7S猫头猫                newPlayList,
6595500cea7S猫头猫                newPlayList.findIndex(it => isSameMediaItem(it, musicItem)),
6605500cea7S猫头猫            );
6615500cea7S猫头猫        }
6625500cea7S猫头猫        const playListItems = newPlayList.map((item, index) =>
6635500cea7S猫头猫            produce(item, draft => {
6645500cea7S猫头猫                draft[timeStampSymbol] = now;
6655500cea7S猫头猫                draft[sortIndexSymbol] = index;
6665500cea7S猫头猫            }),
6675500cea7S猫头猫        );
6685500cea7S猫头猫        setPlayList(
6695500cea7S猫头猫            repeatModeStore.getValue() === MusicRepeatMode.SHUFFLE
6705500cea7S猫头猫                ? shuffle(playListItems)
6715500cea7S猫头猫                : playListItems,
6725500cea7S猫头猫        );
6735500cea7S猫头猫        await play(musicItem, true);
6745500cea7S猫头猫    }
6755500cea7S猫头猫};
6765500cea7S猫头猫
6776f57784cS猫头猫const skipToNext = async () => {
6785500cea7S猫头猫    if (isPlayListEmpty()) {
6795500cea7S猫头猫        setCurrentMusic(null);
6805500cea7S猫头猫        return;
6815500cea7S猫头猫    }
6825500cea7S猫头猫
6835500cea7S猫头猫    await play(getPlayListMusicAt(currentIndex + 1), true);
6845500cea7S猫头猫};
6855500cea7S猫头猫
6865500cea7S猫头猫const skipToPrevious = async () => {
6875500cea7S猫头猫    if (isPlayListEmpty()) {
6885500cea7S猫头猫        setCurrentMusic(null);
6895500cea7S猫头猫        return;
6905500cea7S猫头猫    }
6915500cea7S猫头猫
6926f57784cS猫头猫    await play(
6936f57784cS猫头猫        getPlayListMusicAt(currentIndex === -1 ? 0 : currentIndex - 1),
6946f57784cS猫头猫        true,
6956f57784cS猫头猫    );
6965500cea7S猫头猫};
6975500cea7S猫头猫
6985500cea7S猫头猫/** 修改当前播放的音质 */
6995500cea7S猫头猫const changeQuality = async (newQuality: IMusic.IQualityKey) => {
7005500cea7S猫头猫    // 获取当前的音乐和进度
7015500cea7S猫头猫    if (newQuality === qualityStore.getValue()) {
7025500cea7S猫头猫        return true;
7035500cea7S猫头猫    }
7045500cea7S猫头猫
7055500cea7S猫头猫    // 获取当前歌曲
7065500cea7S猫头猫    const musicItem = currentMusicStore.getValue();
7075500cea7S猫头猫    if (!musicItem) {
7085500cea7S猫头猫        return false;
7095500cea7S猫头猫    }
7105500cea7S猫头猫    try {
7115500cea7S猫头猫        const progress = await ReactNativeTrackPlayer.getProgress();
7125500cea7S猫头猫        const plugin = PluginManager.getByMedia(musicItem);
7135500cea7S猫头猫        const newSource = await plugin?.methods?.getMediaSource(
7145500cea7S猫头猫            musicItem,
7155500cea7S猫头猫            newQuality,
7165500cea7S猫头猫        );
7175500cea7S猫头猫        if (!newSource?.url) {
7185500cea7S猫头猫            throw new Error(PlayFailReason.INVALID_SOURCE);
7195500cea7S猫头猫        }
7205500cea7S猫头猫        if (isCurrentMusic(musicItem)) {
7215500cea7S猫头猫            const playingState = (
7225500cea7S猫头猫                await ReactNativeTrackPlayer.getPlaybackState()
7235500cea7S猫头猫            ).state;
7245500cea7S猫头猫            await setTrackSource(
7255500cea7S猫头猫                mergeProps(musicItem, newSource) as unknown as Track,
7265500cea7S猫头猫                !musicIsPaused(playingState),
7275500cea7S猫头猫            );
7285500cea7S猫头猫
7295500cea7S猫头猫            await ReactNativeTrackPlayer.seekTo(progress.position ?? 0);
7306e000b99S猫头猫            setQuality(newQuality);
7315500cea7S猫头猫        }
7325500cea7S猫头猫        return true;
7335500cea7S猫头猫    } catch {
7345500cea7S猫头猫        // 修改失败
7355500cea7S猫头猫        return false;
7365500cea7S猫头猫    }
7375500cea7S猫头猫};
7385500cea7S猫头猫
7395500cea7S猫头猫enum PlayFailReason {
7405500cea7S猫头猫    /** 禁止移动网络播放 */
7415500cea7S猫头猫    FORBID_CELLUAR_NETWORK_PLAY = 'FORBID_CELLUAR_NETWORK_PLAY',
7425500cea7S猫头猫    /** 播放列表为空 */
7435500cea7S猫头猫    PLAY_LIST_IS_EMPTY = 'PLAY_LIST_IS_EMPTY',
7445500cea7S猫头猫    /** 无效源 */
7455500cea7S猫头猫    INVALID_SOURCE = 'INVALID_SOURCE',
7465500cea7S猫头猫    /** 非当前音乐 */
7475500cea7S猫头猫}
7485500cea7S猫头猫
7495500cea7S猫头猫function useMusicState() {
7505500cea7S猫头猫    const playbackState = usePlaybackState();
7515500cea7S猫头猫
7525500cea7S猫头猫    return playbackState.state;
7535500cea7S猫头猫}
7545500cea7S猫头猫
755f511aee9S猫头猫function getPreviousMusic() {
756f511aee9S猫头猫    const currentMusicItem = currentMusicStore.getValue();
757f511aee9S猫头猫    if (!currentMusicItem) {
758f511aee9S猫头猫        return null;
759f511aee9S猫头猫    }
760f511aee9S猫头猫
761f511aee9S猫头猫    return getPlayListMusicAt(currentIndex - 1);
762f511aee9S猫头猫}
763f511aee9S猫头猫
764f511aee9S猫头猫function getNextMusic() {
765f511aee9S猫头猫    const currentMusicItem = currentMusicStore.getValue();
766f511aee9S猫头猫    if (!currentMusicItem) {
767f511aee9S猫头猫        return null;
768f511aee9S猫头猫    }
769f511aee9S猫头猫
770f511aee9S猫头猫    return getPlayListMusicAt(currentIndex + 1);
771f511aee9S猫头猫}
772f511aee9S猫头猫
7735500cea7S猫头猫const TrackPlayer = {
7745500cea7S猫头猫    setupTrackPlayer,
7755500cea7S猫头猫    usePlayList,
7765500cea7S猫头猫    getPlayList,
7775500cea7S猫头猫    addAll,
7785500cea7S猫头猫    add,
7795500cea7S猫头猫    addNext,
7805500cea7S猫头猫    skipToNext,
7815500cea7S猫头猫    skipToPrevious,
7825500cea7S猫头猫    play,
7835500cea7S猫头猫    playWithReplacePlayList,
7845500cea7S猫头猫    pause,
7855500cea7S猫头猫    remove,
7865500cea7S猫头猫    clear,
7875500cea7S猫头猫    useCurrentMusic: currentMusicStore.useValue,
7885500cea7S猫头猫    getCurrentMusic: currentMusicStore.getValue,
7895500cea7S猫头猫    useRepeatMode: repeatModeStore.useValue,
7905500cea7S猫头猫    getRepeatMode: repeatModeStore.getValue,
7915500cea7S猫头猫    toggleRepeatMode,
7925500cea7S猫头猫    usePlaybackState,
7935500cea7S猫头猫    getProgress: ReactNativeTrackPlayer.getProgress,
7945500cea7S猫头猫    useProgress: useProgress,
7955500cea7S猫头猫    seekTo: ReactNativeTrackPlayer.seekTo,
7965500cea7S猫头猫    changeQuality,
7975500cea7S猫头猫    useCurrentQuality: qualityStore.useValue,
7985500cea7S猫头猫    getCurrentQuality: qualityStore.getValue,
7995500cea7S猫头猫    getRate: ReactNativeTrackPlayer.getRate,
8005500cea7S猫头猫    setRate: ReactNativeTrackPlayer.setRate,
8015500cea7S猫头猫    useMusicState,
8025500cea7S猫头猫    reset: ReactNativeTrackPlayer.reset,
803f511aee9S猫头猫    getPreviousMusic,
804f511aee9S猫头猫    getNextMusic,
8055500cea7S猫头猫};
8065500cea7S猫头猫
8075500cea7S猫头猫export default TrackPlayer;
8085500cea7S猫头猫export {MusicRepeatMode, State as MusicState};
809