AVAudioPlayer认为它不在播放中

问题描述 投票:-1回答:2

我调用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”?

swift avaudioplayer avaudiosession
2个回答
0
投票

之所以这样,是因为您在停止当前音频之前对其进行了初始化。尝试这种方式:-

    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)
        }
    }

0
投票

问题是此行:

        player = try! AVAudioPlayer(contentsOf: url!)

您总是会成为new播放器,即使有一个老播放器正在播放。基本上,您的工作顺序是错误的;如果在播放器已经播放的情况下不想执行任何操作,则在执行其他操作之前,先将if player.isPlaying first放入。

© www.soinside.com 2019 - 2024. All rights reserved.