首页 文章

Swift 2 - AVAudioPlayer不播放音频

提问于
浏览
0

我正试图用AVAudioPlayer播放声音,但它没有播放 . 我尝试了一个设备(iPhone 6s)和模拟器 . 我没有收到任何错误并记录下来 . 当我在audioPlayer.play()之前设置一个断点并跳过它时会播放几秒钟然后停止 . 我的代码:

let soundURL = NSBundle.mainBundle().URLForResource("test", withExtension: "mp3")
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            if let soundURL = soundURL {
                let audioPlayer = try AVAudioPlayer(contentsOfURL: soundURL)
                audioPlayer.volume = 1
                audioPlayer.delegate = self
                audioPlayer.prepareToPlay()
                print(audioPlayer.duration)
                audioPlayer.play()
                print("PLAYED")
            }
        }catch {
            print("Error getting the audio file")
        }

1 回答

  • 0

    这是一个可行的例子 . 我不知道在哪里,与你的其余代码相比,你有你上面显示的代码 . 确保您的设备音量不是静音且已打开...

    //declare these as instance variables
    var AudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("FileName", ofType: "mp3")!)
    var AudioPlayer = AVAudioPlayer()
    
    //inside viewDidLoad establish your AVAudioSession and configure the AudioPlayer with the contents of URL
    override func viewDidLoad() {
       super.viewDidLoad()
    
       do {
           try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            //print("AVAudioSession Category Playback OK")
        do {
            try AVAudioSession.sharedInstance().setActive(true)
              //print("AVAudioSession is Active")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
       } catch let error as NSError {
           print(error.localizedDescription)
       }
    
    
       do {
           try AudioPlayer  = AVAudioPlayer(contentsOfURL: AudioURL, fileTypeHint: nil)
       } catch {
           print("errorin do-try-catch")
       }
    }
    
      //play audio
      @IBAction func playAudio(sender: AnyObject){
          AudioPlayer.play()
      }
    

相关问题