在我的应用程序中,我想将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
返回true。我什么都不能在这里。
您知道问题出在哪里吗?
答案 0 :(得分:0)
在设置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)
}
}