【问题标题】:AVAudioPlayer is not playing in swift. How to fix it?AVAudioPlayer 没有快速播放。如何解决?
【发布时间】:2018-06-30 10:13:30
【问题描述】:

在我的应用程序中,我想在我的应用程序中集成一个 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。我这里什么都做不了。

你知道问题出在哪里吗?

【问题讨论】:

  • 你用的是设备还是模拟器。
  • 我已经直接在我的设备上试过了......
  • 在设置 audioPath 之前在 do 块中设置 try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)try AVAudioSession.sharedInstance().setActive(true)
  • @Quintus 此代码将使此应用准备好接管设备音频
  • @GovindKumawat 哇!你救了我的一天!它工作得很好!谢谢!

标签: swift audio-player


【解决方案1】:

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多