swift - AVAudioPlayer 没有快速播放。如何解决?
问题描述
在我的应用程序中,我想在我的应用程序中集成一个 AVAudioPlayer。但我什么都不能在这里。那是我的代码:
import UIKit
import AVFoundation
class NotenAnsicht: UIViewController{
var PlaybackPlayer:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
PlaybackAudioAufsetzen()
}
func PlaybackAudioAufsetzen(){
do{
let audioPath = Bundle.main.path(forResource: "song", ofType: "mp3")
try PlaybackPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
print("Song set")
}
catch{
print("there was an Error")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func PlaybayStarten(sender:UIButton){
PlaybackPlayer.play()
PlaybackPlayer.volume = 1
print(PlaybackPlayer.isPlaying)
print("Song should play")
}
}
我不知道问题出在哪里。所有函数都被正确调用。并且音频播放器未在本地定义。之后PlaybackPlayer.play()
,PlaybackPlayer.isPlaying
返回真。我只是不能在这里。
你知道问题出在哪里吗?
解决方案
在设置 audioPath 之前设置并在你的 do 块中try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
。try AVAudioSession.sharedInstance().setActive(true)
你的代码应该是这样的。
func PlaybackAudioAufsetzen(){
do{
let audioPath = Bundle.main.path(forResource: "song", ofType: "mp3")
/// this code will make this app ready to takeover the device audio
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try PlaybackPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
print("Song set")
}
catch let error {
print(error.localizedDescription)
}
}
推荐阅读
- python - 嗨,如何根据python中的日期删除AWS中的文件?
- android - Flutter IAP - 您已经拥有此项目的错误
- c++ - 将“指向数组的指针数组”转换为“指向第一个元素的指针数组”
- mysql - MySQL内部连接与同一张表的条件
- substrate - 货物在其自己的 Crate 中使用 Pallet 构建节点模板时出错
- android - 无法使用 Tiktok Video kit sdk Android 分享到 Tiktok
- reactjs - 用于 React 项目的 VS Code 中的 Android 模拟器
- javascript - 未在实例上定义,但在渲染期间引用,但可以按我的意愿工作
- javascript - 如何在渲染组件之前获取要加载的链接?
- sql - ClickHouse - SELECT 行数据太慢