AVAudioPlayer认为它不在播放中
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AVAudioPlayer认为它不在播放中相关的知识,希望对你有一定的参考价值。
我调用superPlay
功能开始播放音频一会儿,稍后我再次调用superPlay
功能停止播放。尽管player.isPlaying
为假,即使知道声音显然在无限循环中播放,但这还是不起作用。我不知道为什么需要帮助!
func superPlay(timeInterval: TimeInterval, soundName: String) {
do {
alarmSound = soundName
//set up audio session
try AVAudiosession.sharedInstance().setCategory(.playAndRecord, options: [.defaultToSpeaker, .duckOthers])
try AVAudioSession.sharedInstance().setActive(true)
let url = Bundle.main.url(forResource: alarmSound, withExtension: "mp3")
player = try! AVAudioPlayer(contentsOf: url!)
player.numberOfLoops = -1
//Start AVAudioPlayer
print(timeInterval)
print(time)
let playbackDelay = timeInterval // must be ≥ 0
if player.isPlaying {
player.stop()
} else {
player.play(atTime: player.deviceCurrentTime + playbackDelay) //time is a TimeInterval after which the audio will start
}
}
catch {
print(error)
}
}
我现在花了几天的时间进行调试。发生的情况是原始播放已分配给特定的AudioPlayer ID,例如,打印内容为:"Optional(<AVAudioPlayer: 0x600002802280>)"
当我再次调用该函数停止播放时,AVAudioPlayer被分配了一个不同的ID,因此它找不到旧播放器仍在播放,而是在旧声音之上播放新声音继续前进。
我不确定如何存储AVAudioPlayer ID,然后调用该函数,以便它检查存储播放器是否为“ .isPlaying”?
答案
之所以这样,是因为您在停止当前音频之前对其进行了初始化。尝试这种方式:-
func superPlay(timeInterval: TimeInterval, soundName: String) {
// If audio is playing already then stop it.
if let audioPlayer = player {
if player.isplaying {
player.stop()
}
}
// Initilize audio player object with new sound
do {
alarmSound = soundName
//set up audio session
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: [.defaultToSpeaker, .duckOthers])
try AVAudioSession.sharedInstance().setActive(true)
let url = Bundle.main.url(forResource: alarmSound, withExtension: "mp3")
player = try! AVAudioPlayer(contentsOf: url!)
player.numberOfLoops = -1
//Start AVAudioPlayer
print(timeInterval)
print(time)
let playbackDelay = timeInterval // must be ≥ 0
player.play(atTime: player.deviceCurrentTime + playbackDelay) //time is a TimeInterval after which the audio will start
}
catch {
print(error)
}
}
另一答案
问题是此行:
player = try! AVAudioPlayer(contentsOf: url!)
您总是会成为new播放器,即使有一个老播放器正在播放。基本上,您的工作顺序是错误的;如果在播放器已经播放的情况下不想执行任何操作,则在执行其他操作之前,先将if player.isPlaying
first放入。
以上是关于AVAudioPlayer认为它不在播放中的主要内容,如果未能解决你的问题,请参考以下文章
iPhone 锁定时,AVAudioPlayer 不在后台播放
如何在 ios5 中播放本地方法的 AVAudioPlayer?