首页 > 解决方案 > 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返回真。我只是不能在这里。

你知道问题出在哪里吗?

标签: swiftaudio-player

解决方案


在设置 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)
    }

}

推荐阅读