Jelajahi Sumber

android部分的channel

cjl_macbook 6 tahun lalu
induk
melakukan
e958142494

+ 4 - 4
android/src/main/java/top/kikt/ijkplayer/Ijk.kt

@@ -18,13 +18,12 @@ class Ijk(private val registry: PluginRegistry.Registrar) : MethodChannel.Method
     val id: Long
         get() = textureEntry.id()
 
-    private val ijkPlayer: IjkMediaPlayer = IjkMediaPlayer()
+    val ijkPlayer: IjkMediaPlayer = IjkMediaPlayer()
     private val mediaPlayer: TextureMediaPlayer
 
     private val methodChannel: MethodChannel = MethodChannel(registry.messenger(), "top.kikt/ijkplayer/$id")
 
-
-    private val eventChannel = MethodChannel(registry.messenger(), "top.kikt/ijkplayer/event/$id")
+    private val notifyChannel: NotifyChannel = NotifyChannel(registry, id, this)
 
     init {
         mediaPlayer = TextureMediaPlayer(ijkPlayer)
@@ -89,7 +88,7 @@ class Ijk(private val registry: PluginRegistry.Registrar) : MethodChannel.Method
         }
     }
 
-    private fun getInfo(): Info {
+    fun getInfo(): Info {
         val duration = ijkPlayer.duration
         val currentPosition = ijkPlayer.currentPosition
         val width = ijkPlayer.videoWidth
@@ -153,6 +152,7 @@ class Ijk(private val registry: PluginRegistry.Registrar) : MethodChannel.Method
     }
 
     fun dispose() {
+        notifyChannel.dispose()
         methodChannel.setMethodCallHandler(null)
         mediaPlayer.stop()
         mediaPlayer.release()

+ 1 - 0
android/src/main/java/top/kikt/ijkplayer/IjkplayerPlugin.kt

@@ -23,6 +23,7 @@ class IjkplayerPlugin(private val registrar: Registrar) : MethodCallHandler {
                     val ijk = manager.create()
                     result.success(ijk.id)
                 } catch (e: Exception) {
+                    e.printStackTrace()
                     result.error("1", "创建失败", e)
                 }
             }

+ 11 - 0
android/src/main/java/top/kikt/ijkplayer/Log.kt

@@ -0,0 +1,11 @@
+package top.kikt.ijkplayer
+
+import android.util.Log
+
+var showLog = true
+
+fun Any.logi(any: Any?) {
+    if (showLog) {
+        Log.i(this::class.java.simpleName, any.toString())
+    }
+}

+ 47 - 0
android/src/main/java/top/kikt/ijkplayer/NotifyChannel.kt

@@ -0,0 +1,47 @@
+package top.kikt.ijkplayer
+
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.PluginRegistry
+
+class NotifyChannel(val registry: PluginRegistry.Registrar, val textureId: Long, val ijk: Ijk) {
+
+    private val player
+        get() = ijk.ijkPlayer
+
+    private val channel = MethodChannel(
+            registry.messenger(),
+            "top.kikt/ijkplayer/event/$textureId"
+    )
+
+    private val info
+        get() = ijk.getInfo().toMap()
+
+    init {
+        player.setOnPreparedListener {
+            logi("prepare $info")
+            channel.invokeMethod("prepare", info)
+        }
+        player.setOnCompletionListener {
+            logi("completion $info")
+        }
+        player.setOnBufferingUpdateListener { mp, percent ->
+            logi("completion buffer update $info $percent")
+        }
+        player.setOnSeekCompleteListener {
+            logi("onSeekCompletion $info")
+        }
+        player.setOnErrorListener { mp, what, extra ->
+            logi("onError $what")
+            false
+        }
+        player.setOnInfoListener { mp, what, extra ->
+            logi("onInfoListener $what")
+            false
+        }
+    }
+
+    fun dispose() {
+        player.resetListeners()
+    }
+
+}

+ 3 - 3
example/android/app/build.gradle

@@ -59,7 +59,7 @@ flutter {
 }
 
 dependencies {
-    testImplementation 'junit:junit:4.12'
-    androidTestImplementation 'com.android.support.test:runner:1.0.2'
-    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
+//    testImplementation 'junit:junit:4.12'
+//    androidTestImplementation 'com.android.support.test:runner:1.0.2'
+//    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
 }

+ 4 - 4
example/ios/Podfile.lock

@@ -9,8 +9,8 @@ PODS:
 
 DEPENDENCIES:
   - Flutter (from `.symlinks/flutter/ios`)
-  - flutter_ijkplayer (from `/Volumes/Evo512/code/flutter/plugins/flutter_ijkplayer/ios/flutter_ijkplayer.podspec`)
-  - photo_manager (from `/Users/cai/.pub-cache/hosted/pub.flutter-io.cn/photo_manager-0.3.2/ios/photo_manager.podspec`)
+  - flutter_ijkplayer (from `/Users/caijinglong/Documents/GitHub/flutter_ijkplayer/ios/flutter_ijkplayer.podspec`)
+  - photo_manager (from `/Users/caijinglong/.pub-cache/hosted/pub.flutter-io.cn/photo_manager-0.3.2/ios/photo_manager.podspec`)
 
 SPEC REPOS:
   https://github.com/cocoapods/specs.git:
@@ -20,9 +20,9 @@ EXTERNAL SOURCES:
   Flutter:
     :path: ".symlinks/flutter/ios"
   flutter_ijkplayer:
-    :path: "/Volumes/Evo512/code/flutter/plugins/flutter_ijkplayer/ios/flutter_ijkplayer.podspec"
+    :path: "/Users/caijinglong/Documents/GitHub/flutter_ijkplayer/ios/flutter_ijkplayer.podspec"
   photo_manager:
-    :path: "/Users/cai/.pub-cache/hosted/pub.flutter-io.cn/photo_manager-0.3.2/ios/photo_manager.podspec"
+    :path: "/Users/caijinglong/.pub-cache/hosted/pub.flutter-io.cn/photo_manager-0.3.2/ios/photo_manager.podspec"
 
 SPEC CHECKSUMS:
   Flutter: 58dd7d1b27887414a370fcccb9e645c08ffd7a6a

+ 3 - 0
example/lib/main.dart

@@ -149,6 +149,9 @@ class HomePageState extends State<HomePage> {
         Timer.periodic(Duration(seconds: 2), (timer) async {
           var info = await controller.getVideoInfo();
           print("info = $info");
+          if (info == null) {
+            return;
+          }
 
           if (info.progress >= 0.95) {
             timer.cancel();

+ 4 - 18
ios/Classes/KKIjkNotifyChannel.m

@@ -91,34 +91,20 @@
 
 - (void)moviePlayBackFinish:(NSNotification *)notification {
     int reason = [[[notification userInfo] valueForKey:IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
+    int type = 2;
     switch (reason) {
         case IJKMPMovieFinishReasonPlaybackEnded:
-//            if ([_infoDelegate isLooping]) {
-//                [_controller setCurrentPlaybackTime:0];
-//                [_controller play];
-//            }
-
+            type = 0;
             break;
-
         case IJKMPMovieFinishReasonUserExited:
-            if (_eventSink) {
-                _eventSink(@{@"event": @"user quit"});
-            }
+            type = 1;
             break;
-
         case IJKMPMovieFinishReasonPlaybackError:
-            if (_eventSink) {
-                _eventSink([FlutterError
-                        errorWithCode:@"VideoError"
-                              message:@"Video finished with error"
-                              details:nil]);
-            }
             break;
-
         default:
             break;
     }
-//    [channel invokeMethod:@"playFinish" arguments:[self getInfo]];
+    [channel invokeMethod:@"finish" arguments:@{@"type": @(type)}];
 }
 
 - (void)loadStateDidChange:(NSNotification *)notification {

+ 6 - 6
lib/src/controller.dart

@@ -11,6 +11,8 @@ class IjkMediaController extends ChangeNotifier {
 
   IJKEventChannel eventChannel;
 
+  bool isPlaying = false;
+
   Future<void> _initIjk() async {
     try {
       var id = await createIjk();
@@ -62,7 +64,7 @@ class IjkMediaController extends ChangeNotifier {
   }
 
   Future<VideoInfo> getVideoInfo() async {
-    Map<String, dynamic> result = await _plugin.getInfo();
+    Map<String, dynamic> result = await _plugin?.getInfo();
     return VideoInfo.fromMap(result);
   }
 }
@@ -98,9 +100,8 @@ class _IjkPlugin {
   }
 
   Future<void> setNetworkDataSource({String uri}) async {
-    // todo
     print("id = $textureId net uri = $uri");
-    channel.invokeMethod("setNetworkDataSource", {"uri": uri});
+    await channel.invokeMethod("setNetworkDataSource", {"uri": uri});
   }
 
   Future<void> setAssetDataSource(String name, String package) async {
@@ -111,17 +112,16 @@ class _IjkPlugin {
     if (package != null) {
       params["package"] = package;
     }
-    channel.invokeMethod("setAssetDataSource", params);
+    await channel.invokeMethod("setAssetDataSource", params);
   }
 
   Future<void> setFileDataSource(String path) async {
     if (!File(path).existsSync()) {
       return Error.fileNotExists;
     }
-    channel.invokeMethod("setFileDataSource", <String, dynamic>{
+    await channel.invokeMethod("setFileDataSource", <String, dynamic>{
       "path": path,
     });
-    // todo
     print("id = $textureId file path = $path");
   }
 

+ 35 - 1
lib/src/ijk_event_channel.dart

@@ -1,4 +1,5 @@
 import 'package:flutter/services.dart';
+import 'package:flutter_ijkplayer/src/video_info.dart';
 
 import './ijkplayer.dart';
 
@@ -25,7 +26,16 @@ class IJKEventChannel {
 
   Future<dynamic> handler(MethodCall call) async {
     switch (call.method) {
-      case "stateChange": // 对应状态变化
+      case "finish": // 对应状态变化
+        var index = call.arguments["type"];
+        var type = FinishType.values[index];
+        onPlayFinish(type);
+        break;
+      case "playStateChange":
+        onPlayStateChange(getInfo(call));
+        break;
+      case "prepare":
+        onPrepare(getInfo(call));
         break;
       default:
         return MissingPluginException(
@@ -33,4 +43,28 @@ class IJKEventChannel {
         );
     }
   }
+
+  VideoInfo getInfo(MethodCall call) {
+    var map = call.arguments.cast<String, dynamic>();
+    return VideoInfo.fromMap(map);
+  }
+
+  void onPlayFinish(FinishType type) {
+    print("onPlayFinish type = $type");
+  }
+
+  void onPlayStateChange(VideoInfo info) {
+    print("onPlayStateChange $info");
+    controller.isPlaying = info.isPlaying;
+  }
+
+  void onPrepare(VideoInfo info) {
+    print("onPrepare $info");
+  }
+}
+
+enum FinishType {
+  playEnd,
+  userExit,
+  error,
 }

+ 4 - 1
lib/src/video_info.dart

@@ -11,7 +11,7 @@ class VideoInfo {
 
   double get radio => width / height;
 
-  double get progress => currentPosition / duration;
+  double get progress => currentPosition ?? 0 / duration ?? 1;
 
   VideoInfo.fromMap(Map<String, dynamic> map) {
     if (map == null) {
@@ -27,6 +27,9 @@ class VideoInfo {
 
   @override
   String toString() {
+    if (_map == null) {
+      return "null";
+    }
     return json.encode(_map);
   }
 }