WKWebView 视频音频播放不能停止的问题

当WKWebView正在播放视频或者音频时ViewController push 或者 present 到下一个controller 之后,视频仍然在后台播放问题解决

网上有两种方式来处理:

第一:调用视频js函数停止播放(世界上那么多网站,鬼知道神马js函数)

第二:在有播放视频的页面进行reload或者退出后加载一个空白地址(细看貌似有道理,但若这个视屏是自动播放的情况,reload就尴尬了,加载一个空白地址也行不通,比方在跳转页面时候停止当前播放器)

整来整去貌似都搞不了,

这里我介绍另一种处理方式,算是比较取巧的做法,想必大伙都知道,app上的播放器只要有一个播放,其它都会被暂停,这里采用的正是这一特性,在后台创建一个唯一的无声 AVAudioPlayer 在需要停止播放器的地方调用一下 -[AVAudioPlayer play] -[AVAudioPlayer pause] 方法

首先,定义一个空的MP3文件,这里采用空文件byte数组直接写在代码里,减少文件关联

static long kEmptyMp3ByteLength = 475;
static Byte kEmptyMp3Byte[] = {73,68,51,3,0,0,0,0,0,47,84,73,84,50,0,0,0,6,0,0,0,101,109,112,116,121,84,69,78,67,0,0,0,8,0,0,0,70,105,115,115,105,111,110,84,76,69,78,0,0,0,3,0,0,0,50,54,255,251,146,100,249,137,132,23,109,192,49,168,127,176,82,205,168,38,52,43,190,13,45,181,7,37,9,119,193,21,54,161,112,176,157,184,51,161,30,71,73,220,100,30,174,33,27,55,130,64,96,169,67,225,174,116,166,199,144,109,15,100,77,132,5,49,248,188,99,59,215,254,182,167,255,247,219,254,136,103,106,152,202,170,254,219,233,163,76,163,250,232,181,245,217,187,219,235,255,191,251,124,243,203,88,250,22,98,5,30,149,52,122,47,98,34,1,128,172,104,248,18,22,4,72,248,128,204,6,241,112,188,50,0,118,151,214,60,77,85,101,90,164,221,107,83,170,189,119,85,215,218,181,117,247,222,135,191,173,90,149,90,150,255,207,49,235,119,123,153,53,165,117,85,228,201,43,114,87,93,48,189,56,242,203,8,90,145,64,22,28,243,80,81,76,109,242,164,245,175,126,53,251,102,127,245,177,159,253,116,58,120,129,155,221,245,60,185,166,171,254,190,109,153,162,76,201,87,78,14,103,65,160,204,138,52,237,180,169,250,55,88,89,89,75,250,70,35,180,38,25,56,56,85,0,187,30,116,73,70,255,32,137,131,9,100,64,168,187,136,50,203,7,100,78,245,127,89,173,118,253,191,39,255,191,254,223,95,191,238,85,238,159,127,245,246,149,255,255,255,255,42,255,247,253,76,228,33,163,70,17,140,29,15,28,240,249,74,49,132,3,161,240,152,213,93,2,20,1,80,72,205,14,14,49,160,134,93,169,235,103,178,215,122,223,189,94,138,150,245,255,183,255,213,255,111,237,229,250,145,202,68,110,103,169,228,177,7,57,56,174,51,130,24,13,13,205,198,26,165,84,233,36,141,157,60,251,151,244,230,119,242,254,12,80,227,231,122,254,159,127,255,124,218,20,10,124,68,116,237,189,186,59,121,228,166,121,9};

AVAudioPlayer 方面采用NSdata来创建,所以需要把这个MP3 byte数组转换成NSData,然后创建

AVAudioPlayer* kEmptyMp3Player(){
    static AVAudioPlayer* kPlayer;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSData *emptyMp3Data = [[NSData alloc] initWithBytes:kEmptyMp3Byte length:kEmptyMp3ByteLength];
        NSError *error;
        kPlayer = [[AVAudioPlayer alloc] initWithData:emptyMp3Data error:&error];
        kPlayer.meteringEnabled = YES;
        kPlayer.volume = 0.0;
    });
    return kPlayer;
}

接下去只要播放这个player,其它地方的视音频播放器就会停止播放

void pauseAllPlayer() {
   AVAudioPlayer *player = kEmptyMp3Player();
   [player play];
   [player pause];
}

你可能感兴趣的:(WKWebView 视频音频播放不能停止的问题)