Skip to content

Instantly share code, notes, and snippets.

@funkenstrahlen
Created May 16, 2016 09:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funkenstrahlen/ba0f97c1fb9f88ee63a44470a8ed7b5f to your computer and use it in GitHub Desktop.
Save funkenstrahlen/ba0f97c1fb9f88ee63a44470a8ed7b5f to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
import AVFoundation
// keep it running forever so it plays audio
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(true)
class AVPlayerTest {
let player = AVPlayer()
let streamurl = NSURL(string: "http://detektor.fm/stream/mp3/musik/")!
func startTest() {
let item = AVPlayerItem(URL: streamurl)
player.replaceCurrentItemWithPlayerItem(item)
player.play()
// give it time to fill buffer
let bufferTime = CMTime(seconds: NSTimeInterval(CMTimeGetSeconds(player.currentItem!.currentTime())).advancedBy(30), preferredTimescale: 1000000000)
player.seekToTime(bufferTime)
NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(timerTickedToPause), userInfo: nil, repeats: false)
printStatus()
}
@objc func timerTickedToPause(timer: NSTimer) {
player.pause()
// pause now for some time. 90s is not enough.
NSTimer.scheduledTimerWithTimeInterval(120, target: self, selector: #selector(timerTickedToPlay), userInfo: nil, repeats: false)
printStatus()
}
@objc func timerTickedToPlay(timer: NSTimer) {
// try to resume playback
printStatus()
player.play()
printStatus()
// check in some seconds if it recovered
NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(timerTickedCheck), userInfo: nil, repeats: false)
}
@objc func timerTickedCheck(timer: NSTimer) {
// it reports rate = 1.0 but is not playing here though!
printStatus()
// recover by creating a new item
// let item = AVPlayerItem(URL: streamurl)
// player.replaceCurrentItemWithPlayerItem(item)
// player.play()
//
// printStatus()
}
func printStatus() {
print("###########")
print("rate: \(player.rate)")
print("playbackLikelyToKeepUp: \(player.currentItem!.playbackLikelyToKeepUp)")
print("playbackBufferEmpty: \(player.currentItem!.playbackBufferEmpty)")
print("playbackBufferFull: \(player.currentItem!.playbackBufferFull)")
switch player.currentItem!.status {
case AVPlayerItemStatus.ReadyToPlay: print("status: READY")
case AVPlayerItemStatus.Failed: print("status: FAILED")
default: break
}
print("###########")
}
}
let test = AVPlayerTest()
test.startTest()
@cgeffect
Copy link

cgeffect commented Sep 8, 2018

I This problem has been bothering me for several days, I met is interrupted, play again, broadcast schedule is normal, but there was no voice, have tried many ways, but couldn't find a solution. Is this problem by the ultimate solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment