AVAudioPlayer在播放的时候不认为是在播放。

问题描述 投票:0回答:1

我叫 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
1个回答
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)
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.