當WKWebView正在播放視頻或者音頻時ViewController push 或者 present 到下一個controller 之后,視頻仍然在后臺播放問題解決
網上有兩種方式來處理:
第一:調用視頻js函數停止播放(世界上那么多網站,鬼知道神馬js函數)
第二:在有播放視頻的頁面進行reload或者退出后加載一個空白地址(細看貌似有道理垃它,但若這個視屏是自動播放的情況操漠,reload就尷尬了干发,加載一個空白地址也行不通薯鼠,比方在跳轉頁面時候停止當前播放器)
整來整去貌似都搞不了,
這里我介紹另一種處理方式昔逗,算是比較取巧的做法,想必大伙都知道篷朵,app上的播放器只要有一個播放勾怒,其它都會被暫停,這里采用的正是這一特性声旺,在后臺創(chuàng)建一個唯一的無聲 AVAudioPlayer 在需要停止播放器的地方調用一下 -[AVAudioPlayer play] -[AVAudioPlayer pause] 方法
首先控硼,定義一個空的MP3文件,這里采用空文件byte數組直接寫在代碼里艾少,減少文件關聯(lián)
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來創(chuàng)建卡乾,所以需要把這個MP3 byte數組轉換成NSData,然后創(chuàng)建
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];
}