@a-cloud-guru/react-native-music-control 中文文档教程

发布于 3年前 浏览 35 项目主页 更新于 3年前

react-native-music-control

React Native Music Control 是一个模块,用于启用远程控制并在 Android 和 iOS 的锁定屏幕和通知区域中显示“正在播放”信息。

​​React Native Sound 配合良好。


Mix between:

Project using this repo:

iOS lockscreen


Installation Process

  1. Add it to your project
npm install react-native-music-control --save
  1. Link it to your project

Linking on iOS

Automatic

react-native link

:警告:您必须在 XCode 项目设置中启用音频背景模式:

XCode bqckground mode enabled

Manual

在 XCode 中,右键单击 Libraries。 单击将文件添加到“[您的项目]”。 导航到 node_modules/react-native-music-control。 添加文件 MusicControl.xcodeproj。

在项目导航器中,选择您的项目。 单击构建目标。 单击构建阶段。 展开链接二进制文件与库。 单击加号按钮并在工作区下添加 libMusicControl.a。

CocoaPods

pod 'react-native-music-control', :path => '../node_modules/react-native-music-control'

在 /ios 文件夹中运行 pod install


Linking on Android

Automatic

react-native link

将以下内容添加到您的项目 AndroidManifest.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Manual

android/app/build.gradle

dependencies {
    ...
    compile "com.facebook.react:react-native:+"  // From node_modules
+   compile project(':react-native-music-control')
}

android/settings.gradle

...
include ':app'
+include ':react-native-music-control'
+project(':react-native-music-control').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-music-control/android')

MainApplication.java

+import com.tanguyantoine.react.MusicControl;

public class MainApplication extends Application implements ReactApplication {
    //......

    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
+           new MusicControl(),
            new MainReactPackage()
        );
    }

    //......
  }

将以下内容添加到您的项目 AndroidManifest.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Troubleshooting

一些用户在编译 Android 版本时报告了此错误:

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

的末尾复制此行

要解决此问题,请在应用程序 build.gradle android/ app/build.gradle

+configurations.all {
+    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
+        def requested = details.requested
+        if (requested.group == 'com.android.support') {
+            if (!requested.name.startsWith("multidex")) {
+                details.useVersion '26.0.1'
+            }
+        }
+    }
+}

Usage

import MusicControl from 'react-native-music-control';

Enable and Disable controls

iOS:锁屏

Android:通知和外部设备(智能手表、汽车)

// Basic Controls
MusicControl.enableControl('play', true)
MusicControl.enableControl('pause', true)
MusicControl.enableControl('stop', false)
MusicControl.enableControl('nextTrack', true)
MusicControl.enableControl('previousTrack', false)

// Changing track position on lockscreen
MusicControl.enableControl('changePlaybackPosition', true)

// Seeking
MusicControl.enableControl('seekForward', false) // iOS only
MusicControl.enableControl('seekBackward', false) // iOS only
MusicControl.enableControl('seek', false) // Android only
MusicControl.enableControl('skipForward', false)
MusicControl.enableControl('skipBackward', false)

// Android Specific Options
MusicControl.enableControl('setRating', false)
MusicControl.enableControl('volume', true) // Only affected when remoteVolume is enabled
MusicControl.enableControl('remoteVolume', false)

// iOS Specific Options
MusicControl.enableControl('enableLanguageOption', false)
MusicControl.enableControl('disableLanguageOption', false)

skipBackwardskipForward 控件接受带有 interval

MusicControl.enableControl('skipBackward', true, {interval: 15}))
MusicControl.enableControl('skipForward', true, {interval: 30}))

Now Playing

的额外配置选项:setNowPlaying 方法启用音乐控件。 要禁用它们,请使用 resetNowPlaying()

您应该在播放声音后调用此方法。

对于 Android 的评级系统,删除未评级曲目的 rating 值,为 RATINGHEART 或 RATINGTHUMBSUPDOWN 使用布尔值,并为其他类型。

注意:要使用自定义类型,您必须在调用此函数之前使用updatePlayback 定义类型。

MusicControl.setNowPlaying({
  title: 'Billie Jean',
  artwork: 'https://i.imgur.com/e1cpwdo.png', // URL or RN's image require()
  artist: 'Michael Jackson',
  album: 'Thriller',
  genre: 'Post-disco, Rhythm and Blues, Funk, Dance-pop',
  duration: 294, // (Seconds)
  description: '', // Android Only
  color: 0xFFFFFF, // Notification Color - Android Only
  date: '1983-01-02T00:00:00Z', // Release Date (RFC 3339) - Android Only
  rating: 84, // Android Only (Boolean or Number depending on the type)
  notificationIcon: 'my_custom_icon' // Android Only (String), Android Drawable resource name for a custom notification icon
})

Update Playback

调用 updatePlayback 方法时不需要设置所有属性,但您应该始终设置 elapsedTime 以获得 iOS 支持和 Android 上更好的性能。

您无需重复调用此方法来更新 elapsedTime - 仅在需要更新任何其他属性时调用它。

MusicControl.updatePlayback({
  state: MusicControl.STATE_PLAYING, // (STATE_ERROR, STATE_STOPPED, STATE_PLAYING, STATE_PAUSED, STATE_BUFFERING)
  speed: 1, // Playback Rate
  elapsedTime: 103, // (Seconds)
  bufferedTime: 200, // Android Only (Seconds)
  volume: 10, // Android Only (Number from 0 to maxVolume) - Only used when remoteVolume is enabled
  maxVolume: 10, // Android Only (Number) - Only used when remoteVolume is enabled
  rating: MusicControl.RATING_PERCENTAGE // Android Only (RATING_HEART, RATING_THUMBS_UP_DOWN, RATING_3_STARS, RATING_4_STARS, RATING_5_STARS, RATING_PERCENTAGE)
})

示例

// Changes the state to paused
MusicControl.updatePlayback({
  state: MusicControl.STATE_PAUSED,
  elapsedTime: 135
})

// Changes the volume
MusicControl.updatePlayback({
  volume: 9, // Android Only
  elapsedTime: 167
})

Reset Now Playing

重置并隐藏音乐控件。

MusicControl.resetNowPlaying()

Stop Controls

重置、隐藏音乐控件并禁用所有功能。

MusicControl.stopControl()

Android 上还有一个closeNotification 控件控制音频播放通知的滑动行为,并通过when 键接受额外的配置选项:

// Always allow user to close notification on swipe
MusicControl.enableControl('closeNotification', true, {when: 'always'})

// Default - Allow user to close notification on swipe when audio is paused
MusicControl.enableControl('closeNotification', true, {when: 'paused'})

// Never allow user to close notification on swipe
MusicControl.enableControl('closeNotification', true, {when: 'never'})

Register to Events

componentDidMount() {
    MusicControl.enableBackgroundMode(true);

    // on iOS, pause playback during audio interruptions (incoming calls) and resume afterwards.
    // As of {{ INSERT NEXT VERSION HERE}} works for android aswell.
    MusicControl.handleAudioInterruptions(true);

    MusicControl.on('play', ()=> {
      this.props.dispatch(playRemoteControl());
    })

    // on iOS this event will also be triggered by audio router change events
    // happening when headphones are unplugged or a bluetooth audio peripheral disconnects from the device
    MusicControl.on('pause', ()=> {
      this.props.dispatch(pauseRemoteControl());
    })

    MusicControl.on('stop', ()=> {
      this.props.dispatch(stopRemoteControl());
    })

    MusicControl.on('nextTrack', ()=> {
      this.props.dispatch(nextRemoteControl());
    })

    MusicControl.on('previousTrack', ()=> {
      this.props.dispatch(previousRemoteControl());
    })

    MusicControl.on('changePlaybackPosition', ()=> {
      this.props.dispatch(updateRemoteControl());
    })

    MusicControl.on('seekForward', ()=> {});
    MusicControl.on('seekBackward', ()=> {});

    MusicControl.on('seek', (pos)=> {}); // Android only (Seconds)
    MusicControl.on('volume', (volume)=> {}); // Android only (0 to maxVolume) - Only fired when remoteVolume is enabled

    // Android Only (Boolean for RATING_HEART or RATING_THUMBS_UP_DOWN, Number for other types)
    MusicControl.on('setRating', (rating)=> {});

    MusicControl.on('togglePlayPause', ()=> {}); // iOS only
    MusicControl.on('enableLanguageOption', ()=> {}); // iOS only
    MusicControl.on('disableLanguageOption', ()=> {}); // iOS only
    MusicControl.on('skipForward', ()=> {});
    MusicControl.on('skipBackward', ()=> {});

    // Android Only
    MusicControl.on('closeNotification', ()=> {
      this.props.dispatch(onAudioEnd());
    })
}

注意 :同时启用“播放”和“暂停”控件将只显示一个图标——播放或暂停图标。 音乐控制通知将根据通过 updatePlayback 方法设置的状态切换显示哪一个。 当状态为 MusicControl.STATE_PLAYING 时,它将显示暂停图标,而当状态为 MusicControl.STATE_PAUSED 时,它将显示播放图标。


Important Notes

  • Android only supports the intervals 5, 10, & 30, while iOS supports any number
  • The interval value only changes what number displays in the UI, the actual logic to skip forward or backward by a given amount must be implemented in the appropriate callbacks
  • When using react-native-sound for audio playback, make sure that on iOS mixWithOthers is set to false in Sound.setCategory(value, mixWithOthers). MusicControl will not work on a real device when this is set to true.
  • For lockscreen controls to appear enabled instead of greyed out, the accompanying listener for each control that you want to display on the lock screen must contain a valid function:
MusicControl.on('play', () => {
  // A valid funcion must be present
  player.play()
})

Customization

可以自定义 Android 通知中使用的图标。 默认情况下,您可以使用文件名 music_control_icon 将可绘制资源添加到包中,通知将使用您的自定义图标。 如果您需要指定自定义图标名称,或在运行时更改通知图标,setNowPlaying 函数会在 notificationIcon 属性中接受 Android 可绘制资源名称的字符串。 请记住,就像使用 music_control_icon 一样,指定的资源必须位于 Android 应用的可绘制包中。

  MusicControl.setCustomNotificationIcon('my_custom_icon');

TODOs

  • [x] Android support
  • [ ] Test
  • [x] Publish package
  • [x] React-Native link configuration for Android
  • [x] React-Native link configuration for iOS
  • [x] Android : Handle remote events
  • [x] Android : Display cover artwork

Contributing

Of coursssssseeeeee. I'm waiting your PR :)

react-native-music-control

React Native Music Control is a module to enable remote controls and display "Now Playing" info on the lock screen and in the notification area on Android and iOS.

Plays well with React Native Sound.


Mix between:

Project using this repo:

iOS lockscreen


Installation Process

  1. Add it to your project
npm install react-native-music-control --save
  1. Link it to your project

Linking on iOS

Automatic

react-native link

:warning: You must enable Audio Background mode in XCode project settings :

XCode bqckground mode enabled

Manual

In XCode, right click Libraries. Click Add Files to "[Your project]". Navigate to node_modules/react-native-music-control. Add the file MusicControl.xcodeproj.

In the Project Navigator, select your project. Click the build target. Click Build Phases. Expand Link Binary With Libraries. Click the plus button and add libMusicControl.a under Workspace.

CocoaPods

pod 'react-native-music-control', :path => '../node_modules/react-native-music-control'

Run pod install in /ios folder.


Linking on Android

Automatic

react-native link

Add following to your project AndroidManifest.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Manual

android/app/build.gradle

dependencies {
    ...
    compile "com.facebook.react:react-native:+"  // From node_modules
+   compile project(':react-native-music-control')
}

android/settings.gradle

...
include ':app'
+include ':react-native-music-control'
+project(':react-native-music-control').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-music-control/android')

MainApplication.java

+import com.tanguyantoine.react.MusicControl;

public class MainApplication extends Application implements ReactApplication {
    //......

    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
+           new MusicControl(),
            new MainReactPackage()
        );
    }

    //......
  }

Add following to your project AndroidManifest.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Troubleshooting

Some users reported this error while compiling the Android version:

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

To solve this, issue just copy this line at the end of your application build.gradle

android/app/build.gradle

+configurations.all {
+    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
+        def requested = details.requested
+        if (requested.group == 'com.android.support') {
+            if (!requested.name.startsWith("multidex")) {
+                details.useVersion '26.0.1'
+            }
+        }
+    }
+}

Usage

import MusicControl from 'react-native-music-control';

Enable and Disable controls

iOS: Lockscreen

Android: Notification and external devices (smartwatches, cars)

// Basic Controls
MusicControl.enableControl('play', true)
MusicControl.enableControl('pause', true)
MusicControl.enableControl('stop', false)
MusicControl.enableControl('nextTrack', true)
MusicControl.enableControl('previousTrack', false)

// Changing track position on lockscreen
MusicControl.enableControl('changePlaybackPosition', true)

// Seeking
MusicControl.enableControl('seekForward', false) // iOS only
MusicControl.enableControl('seekBackward', false) // iOS only
MusicControl.enableControl('seek', false) // Android only
MusicControl.enableControl('skipForward', false)
MusicControl.enableControl('skipBackward', false)

// Android Specific Options
MusicControl.enableControl('setRating', false)
MusicControl.enableControl('volume', true) // Only affected when remoteVolume is enabled
MusicControl.enableControl('remoteVolume', false)

// iOS Specific Options
MusicControl.enableControl('enableLanguageOption', false)
MusicControl.enableControl('disableLanguageOption', false)

skipBackward and skipForward controls on accept additional configuration options with interval key:

MusicControl.enableControl('skipBackward', true, {interval: 15}))
MusicControl.enableControl('skipForward', true, {interval: 30}))

Now Playing

The setNowPlaying method enables the music controls. To disable them, use resetNowPlaying().

You should call this method after a sound is playing.

For Android's rating system, remove the rating value for unrated tracks, use a boolean for RATINGHEART or RATINGTHUMBSUPDOWN and use a number for other types.

Note: To use custom types, you have to define the type with updatePlayback before calling this function.

MusicControl.setNowPlaying({
  title: 'Billie Jean',
  artwork: 'https://i.imgur.com/e1cpwdo.png', // URL or RN's image require()
  artist: 'Michael Jackson',
  album: 'Thriller',
  genre: 'Post-disco, Rhythm and Blues, Funk, Dance-pop',
  duration: 294, // (Seconds)
  description: '', // Android Only
  color: 0xFFFFFF, // Notification Color - Android Only
  date: '1983-01-02T00:00:00Z', // Release Date (RFC 3339) - Android Only
  rating: 84, // Android Only (Boolean or Number depending on the type)
  notificationIcon: 'my_custom_icon' // Android Only (String), Android Drawable resource name for a custom notification icon
})

Update Playback

You don't need to set all properties when calling the updatePlayback method, but you should always set elapsedTime for iOS support and better performance on Android.

You don't need to call this method repeatedly to update the elapsedTime -- only call it when you need to update any other property.

MusicControl.updatePlayback({
  state: MusicControl.STATE_PLAYING, // (STATE_ERROR, STATE_STOPPED, STATE_PLAYING, STATE_PAUSED, STATE_BUFFERING)
  speed: 1, // Playback Rate
  elapsedTime: 103, // (Seconds)
  bufferedTime: 200, // Android Only (Seconds)
  volume: 10, // Android Only (Number from 0 to maxVolume) - Only used when remoteVolume is enabled
  maxVolume: 10, // Android Only (Number) - Only used when remoteVolume is enabled
  rating: MusicControl.RATING_PERCENTAGE // Android Only (RATING_HEART, RATING_THUMBS_UP_DOWN, RATING_3_STARS, RATING_4_STARS, RATING_5_STARS, RATING_PERCENTAGE)
})

Examples

// Changes the state to paused
MusicControl.updatePlayback({
  state: MusicControl.STATE_PAUSED,
  elapsedTime: 135
})

// Changes the volume
MusicControl.updatePlayback({
  volume: 9, // Android Only
  elapsedTime: 167
})

Reset Now Playing

Resets and hides the music controls.

MusicControl.resetNowPlaying()

Stop Controls

Resets, hides the music controls and disables everything.

MusicControl.stopControl()

There is also a closeNotification control on Android controls the swipe behavior of the audio playing notification, and accepts additional configuration options with the when key:

// Always allow user to close notification on swipe
MusicControl.enableControl('closeNotification', true, {when: 'always'})

// Default - Allow user to close notification on swipe when audio is paused
MusicControl.enableControl('closeNotification', true, {when: 'paused'})

// Never allow user to close notification on swipe
MusicControl.enableControl('closeNotification', true, {when: 'never'})

Register to Events

componentDidMount() {
    MusicControl.enableBackgroundMode(true);

    // on iOS, pause playback during audio interruptions (incoming calls) and resume afterwards.
    // As of {{ INSERT NEXT VERSION HERE}} works for android aswell.
    MusicControl.handleAudioInterruptions(true);

    MusicControl.on('play', ()=> {
      this.props.dispatch(playRemoteControl());
    })

    // on iOS this event will also be triggered by audio router change events
    // happening when headphones are unplugged or a bluetooth audio peripheral disconnects from the device
    MusicControl.on('pause', ()=> {
      this.props.dispatch(pauseRemoteControl());
    })

    MusicControl.on('stop', ()=> {
      this.props.dispatch(stopRemoteControl());
    })

    MusicControl.on('nextTrack', ()=> {
      this.props.dispatch(nextRemoteControl());
    })

    MusicControl.on('previousTrack', ()=> {
      this.props.dispatch(previousRemoteControl());
    })

    MusicControl.on('changePlaybackPosition', ()=> {
      this.props.dispatch(updateRemoteControl());
    })

    MusicControl.on('seekForward', ()=> {});
    MusicControl.on('seekBackward', ()=> {});

    MusicControl.on('seek', (pos)=> {}); // Android only (Seconds)
    MusicControl.on('volume', (volume)=> {}); // Android only (0 to maxVolume) - Only fired when remoteVolume is enabled

    // Android Only (Boolean for RATING_HEART or RATING_THUMBS_UP_DOWN, Number for other types)
    MusicControl.on('setRating', (rating)=> {});

    MusicControl.on('togglePlayPause', ()=> {}); // iOS only
    MusicControl.on('enableLanguageOption', ()=> {}); // iOS only
    MusicControl.on('disableLanguageOption', ()=> {}); // iOS only
    MusicControl.on('skipForward', ()=> {});
    MusicControl.on('skipBackward', ()=> {});

    // Android Only
    MusicControl.on('closeNotification', ()=> {
      this.props.dispatch(onAudioEnd());
    })
}

Note: Enabling both the 'play' and 'pause' controls will only show one icon -- either a play or a pause icon. The Music Control notification will switch which one is displayed based on the state set via the updatePlayback method. While the state is MusicControl.STATE_PLAYING it will show the pause icon, and while the state is MusicControl.STATE_PAUSED it will show the play icon.


Important Notes

  • Android only supports the intervals 5, 10, & 30, while iOS supports any number
  • The interval value only changes what number displays in the UI, the actual logic to skip forward or backward by a given amount must be implemented in the appropriate callbacks
  • When using react-native-sound for audio playback, make sure that on iOS mixWithOthers is set to false in Sound.setCategory(value, mixWithOthers). MusicControl will not work on a real device when this is set to true.
  • For lockscreen controls to appear enabled instead of greyed out, the accompanying listener for each control that you want to display on the lock screen must contain a valid function:
MusicControl.on('play', () => {
  // A valid funcion must be present
  player.play()
})

Customization

It is possible to customize the icon used in the notification on Android. By default you can add a drawable resource to your package with the file name music_control_icon and the notification will use your custom icon. If you need to specify a custom icon name, or change your notification icon during runtime, the setNowPlaying function accepts a string for an Android drawable resource name in the notificationIcon prop. Keep in mind that just like with music_control_icon the resource specified has to be in the drawable package of your Android app.

  MusicControl.setCustomNotificationIcon('my_custom_icon');

TODOs

  • [x] Android support
  • [ ] Test
  • [x] Publish package
  • [x] React-Native link configuration for Android
  • [x] React-Native link configuration for iOS
  • [x] Android : Handle remote events
  • [x] Android : Display cover artwork

Contributing

Of coursssssseeeeee. I'm waiting your PR :)

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文