play static method

dynamic play(
  1. Uint8List? data,
  2. bool interrupt,
  3. String? text
)

播放PCM格式数据*

Implementation

static play(Uint8List? data,bool interrupt,String? text) async {
  Log.i(tag, "playPCM:text:$text");

  Log.i(tag, "playPCM:interrupt:$interrupt");
  //打断播放
  if(interrupt){
    await stopPlay();
  }else{
    //如果正在播放则加入队列
    Log.i(tag, "playPCM:isPlaying:$_isPlaying");
    if(_isPlaying){
      PlayItem playItem=PlayItem();
      playItem.data=data;
      playItem.text=text;
      _playQueue.add(playItem);
      return;
    }
  }

  _isPlaying=true;

  await onPlayStart();

  // 手动激活AVAudioSession
  // 电话通话中setActive会报错但不崩溃,不会继续往下运行
  // 需要await,否则不能捕捉错误且往下运行
  try{
    await Common.setAudioSessionActive(true);
  }catch(e){
    //PlatformException(561017449, Session activation failed, null, null)
    Log.i(tag, "playPCM:exception:$e");
    //不能正常setActive,则立即结束播放
    Log.i(tag, "playPCM:stopPlay");
    await stopPlay();
    return;
  }

  if(text!=null){//播放文本
    Log.i(tag, "playPCM:play text");
    await FlutterTTSHandler.play(text,
          (){
            Log.i(tag, "playPCM:startHandler");
          },
          () async {//ios被打断播放也会回调该方法,android不会
            Log.i(tag, "playPCM:completionHandler");
            await onFlutterTTSPlayFinsihed();
          },
          () async {//android被打断播放会回调该方法
            //被电话打断会回调这里,电话结束后会自动重新播放,此时无法stop,调用下一个播放会被加入播放队列等待播放,然后变成可以打断,但是打断后再也不能播放
            Log.i(tag, "playPCM:cancelHandler");
          },
          (){
            Log.i(tag, "playPCM:pauseHandler");
          },
          (){
            Log.i(tag, "playPCM:continueHandler");
          },
          (message) {
            Log.i(tag, "playPCM:errorHandler:$message");
          },
          (arg1, arg2, arg3, arg4) async {
            Log.i(tag, "playPCM:processHandler");
            Log.i(tag, "playPCM:processHandler:arg1:$arg1");
            Log.i(tag, "playPCM:processHandler:arg2:$arg2.toString()");
            Log.i(tag, "playPCM:processHandler:arg3:$arg3.toString()");
            Log.i(tag, "playPCM:processHandler:arg4:$arg4");

            //播放过程中检查是否能setAudioSessionActive,如果不能则说明被电话打断,此时需要结束播放,然后会会回调completionHandler,否则会回调cancelHandler并导致异常
            try{
              Log.i(tag, "playPCM:processHandler:setAudioSessionActive");
              await Common.setAudioSessionActive(true);
              Log.i(tag, "playPCM:processHandler:setAudioSessionActive:end");
            }catch(e){
              Log.i(tag, "playPCM:setAudioSessionActive:excetion:stopplay");
              await stopPlay();
            }
          }
    );
  }else{//播放语音
    //开始播放
    await soundPlayer.startPlayer(fromDataBuffer:data,codec:Codec.pcm16,sampleRate:8000,whenFinished: () async {
      await onPlayFinsihed();
    });
    Log.i(tag, "playPCM:startPlayer");
  }
}