2

我正在使用此代码播放音频。我的代码在所有耳机型号的 iOS 14 上都能正常工作,但是当客户将他们的设备更新到 iOS 15 并使用 AirPods Pro 时,没有音频文件播放。在其他 AirPods 型号上以及通过 iPhone 扬声器播放音频文件时,一切正常。发生了什么。如何解决?

更新:

经过漫长的等待,我得到了 AirPods Pro。起初我删除了那条线setupMediaPlayerNotificationView(true),应用程序播放的声音很好。但是锁定屏幕上的一些功能被删除了。应用程序中的这条线没有声音。在 App Store 中,我有 3 个具有相同代码的应用程序。在 ios 15 之后,只有一个工作。而且我不明白代码相同的原因是什么。为什么其他人不工作?但事实证明,该应用程序的名称中有 1 个单词 - Build Settings -> Product Name -> "myAppName". 其余的人说了几句话。当我将它们重命名为 1 个字时,一切正常。声音播放不错。它以前如何?我还是不明白?谁有版本,分享一下。

代码:

 let url = Bundle.main.url(forResource: "\(masterIndex)0", withExtension: "m4a")!
            
     do {
                
     audioPlayer = try AVAudioPlayer(contentsOf: url)
     audioPlayer.delegate = self
     audioPlayer.prepareToPlay()
     play(sender:AnyObject.self as AnyObject)
                
     setupMediaPlayerNotificationView(true)
     lockScreen()
                
     } catch {
                
 }

其他代码:

func lockScreen() {
        
    var albumArtwork : MPMediaItemArtwork!
    let image:UIImage = UIImage(named: "infoImage")!
        
    albumArtwork = MPMediaItemArtwork.init(boundsSize: image.size, requestHandler: { (size) -> UIImage in
        return image
    })
        
    let infotitle = "\(firstArray[index])"
        
    MPNowPlayingInfoCenter.default().nowPlayingInfo = [
        MPMediaItemPropertyArtist : "",
        MPMediaItemPropertyTitle : infotitle,
        MPMediaItemPropertyArtwork : albumArtwork,
        MPMediaItemPropertyAlbumTitle : "",
        MPNowPlayingInfoPropertyElapsedPlaybackTime : Int(audioPlayer.currentTime),
        MPMediaItemPropertyPlaybackDuration: Int(audioPlayer.duration)]
        
}
    
@objc func lockScreenPlay(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
    self.audioPlayer.play()
    self.lockScreen()
    self.playButton.setImage(UIImage(named: "pause.png"), for: UIControlState.normal)
    return .success
}
    
@objc func lockScreenPause(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
    self.audioPlayer.pause()
    self.lockScreen()
    self.playButton.setImage(UIImage(named: "play.png"), for: UIControlState.normal)
    return .success
}
    
@objc func lockScreenFastForward(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
    var time: TimeInterval = audioPlayer.currentTime
    time += 15.0
    if time > audioPlayer.duration {
        audioPlayerDidFinishPlaying(audioPlayer, successfully: true)
    } else {
        audioPlayer.currentTime = time
        updateTime()
    }
        self.lockScreen()
        return .success
    }
    
@objc func lockScreenFastBackward(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
    var time: TimeInterval = audioPlayer.currentTime
    time -= 15.0
    if time < 0 {
        audioPlayer.currentTime = 0
        updateTime()
    } else {
        audioPlayer.currentTime = time
        updateTime()
    }
        self.lockScreen()
        return .success
    }
    
@objc func changedThumbSlider(_ event: MPChangePlaybackPositionCommandEvent) -> MPRemoteCommandHandlerStatus {
    let time = event.positionTime
    audioPlayer.currentTime = TimeInterval(time)
    self.lockScreen()
    return .success
}
    
func setupMediaPlayerNotificationView(_ enable: Bool)  {
    let commandCenter = MPRemoteCommandCenter.shared()
    if enable {
        commandCenter.playCommand.addTarget(self, action: #selector(lockScreenPlay))
        commandCenter.pauseCommand.addTarget(self, action: #selector(lockScreenPause))
        commandCenter.skipForwardCommand.preferredIntervals = [15]
        commandCenter.skipForwardCommand.addTarget(self, action: #selector(lockScreenFastForward))
        commandCenter.skipBackwardCommand.preferredIntervals = [15]
        commandCenter.skipBackwardCommand.addTarget(self, action: #selector(lockScreenFastBackward))
        commandCenter.changePlaybackPositionCommand.addTarget(self, action: #selector(self.changedThumbSlider(_:)))
    } else {
        commandCenter.playCommand.removeTarget(self, action: #selector(lockScreenPlay))
        commandCenter.pauseCommand.removeTarget(self, action: #selector(lockScreenPause))
        commandCenter.skipForwardCommand.removeTarget(self, action: #selector(lockScreenFastForward))
        commandCenter.skipBackwardCommand.removeTarget(self, action: #selector(lockScreenFastBackward))
        commandCenter.changePlaybackPositionCommand.removeTarget(self, action: #selector(self.changedThumbSlider(_:)))
    }
}

@IBAction func play(sender: AnyObject) {
        if !audioPlayer.isPlaying{
            
            animationStatus()
            
            audioPlayer.play()
            slider.maximumValue = Float(audioPlayer.duration)
            timer = Timer(timeInterval: 0.1, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
            RunLoop.main.add(timer!, forMode: .commonModes)
            restorePlayerCurrentTime()
            playButton.setImage(UIImage(named: "pause.png"), for: UIControlState.normal)
        } else {
            
            animationStatus()
            
            audioPlayer.pause()
            playButton.setImage(UIImage(named: "play.png"), for: UIControlState.normal)
            timer?.invalidate()
        }
    }
    
    @IBAction func fastForward(sender: AnyObject) {
        var time: TimeInterval = audioPlayer.currentTime
        time += 15.0 // Go Forward by 15 Seconds
        if time > audioPlayer.duration {
            audioPlayerDidFinishPlaying(audioPlayer, successfully: true)
        } else {
            audioPlayer.currentTime = time
            updateTime()
        }
        self.lockScreen()
    }
    
    @IBAction func fastBackward(sender: AnyObject) {
        var time: TimeInterval = audioPlayer.currentTime
        time -= 15.0 // Go Back by 15 Seconds
        if time < 0 {
            audioPlayer.currentTime = 0
            updateTime()
        } else {
            audioPlayer.currentTime = time
            updateTime()
        }
        self.lockScreen()
    } 

private func restorePlayerCurrentTime() {
        let currentTimeFromUserDefaults : Double? = UserDefaults.standard.value(forKey: "currentTime\(masterIndex)\(index)") as! Double?
        if let currentTimeFromUserDefaultsValue = currentTimeFromUserDefaults {
            audioPlayer.currentTime = currentTimeFromUserDefaultsValue
            slider.value = Float.init(audioPlayer.currentTime)
        }
    }
    
    @objc func updateTime() {
        let currentTime = Int(audioPlayer.currentTime)
        let minutes = currentTime/60
        let seconds = currentTime - minutes * 60
        
        let durationTime = Int(audioPlayer.duration) - Int(audioPlayer.currentTime)
        let minutes1 = durationTime/60
        let seconds1 = durationTime - minutes1 * 60
        
        timeElapsed.text = NSString(format: "%02d:%02d", minutes,seconds) as String
        timeDuration.text = NSString(format: "-%02d:%02d", minutes1,seconds1) as String
        
        UserDefaults.standard.set(currentTime, forKey: "currentTime\(masterIndex)\(index)")
        UserDefaults.standard.set(durationTime, forKey: "durationTime\(masterIndex)\(index)")
        
        slider.value = Float.init(audioPlayer.currentTime)
    }
    
    func audioPlayerDidFinishPlaying(_ audioPlayer: AVAudioPlayer, successfully flag: Bool) {
        
        let currentTime = 0
        let durationTime = 0.1
        UserDefaults.standard.set(currentTime, forKey: "currentTime\(masterIndex)\(index)")
        UserDefaults.standard.set(durationTime, forKey: "durationTime\(masterIndex)\(index)")
        slider.value = Float.init(audioPlayer.currentTime)
        timer?.invalidate()
        
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentDirectoryPath:String = path[0]
        let fileManager = FileManager()
        let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/\(masterIndex)/\(index+1).mp3"))
        
        if fileManager.fileExists(atPath: destinationURLForFile.path){
            
            if endOfChapterSleepTimer == true {
                endOfChapterSleepTimer = false
            } else {
                index = index + 1
                viewDidLoad()
            }
            
        } else {
            
        }
    }

func animationStatus() {
        let vinylLayer = vinylView.layer
        pause = !pause
        if pause {
            pauseLayer(layer: vinylLayer)
        } else {
            if vinylStatus == "true" {
                resumeLayer(layer: vinylLayer)
            } else {
                rotateImageView()
                resumeLayer(layer: vinylLayer)
            }
        }
    }
    
    private func rotateImageView() {
        vinylStatus = "true"
        
        UIView.animate(withDuration: 3, delay: 0, options: .curveLinear, animations: {
            self.vinylView.transform = self.vinylView.transform.rotated(by: .pi / 2)
        }) { (finished) in
            if finished {
                self.rotateImageView()
            }
        }
    }
4

1 回答 1

0

可能是iOS 15的问题?
我找到了一些用于搜索查询的论文:“sound doesn't play AirPods Pro on ios 15”: one , tow , three
据我了解,此问题已在 iOS 15.1 中修复。有时 Apple 会犯错误(例如,每次更新 Xcode :) )

于 2021-11-14T10:49:51.297 回答