2016-03-15 87 views
0

我試圖播放聲音與AVAudioPlayer,但它不能播放。我試了一個設備(iPhone 6s)和模擬器。我沒有收到任何錯誤,並將其記錄下來。當我在audioPlayer.play()之前設置一個斷點並跳過時,它會播放幾秒鐘,然後停止。我的代碼:斯威夫特2 - AVAudioPlayer不播放音頻

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") 
     } 
+0

代碼的其餘部分顯示的代碼在哪裏?這一切都在viewDidLoad? – MikeG

回答

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() 
    }