2015-06-25 75 views
0

我已經在我的模擬器以及我的手機和多個mp3文件上運行這個應用程序,但是我無法從應用程序輸出聲音。我已將mp3文件包含在支持的文件中。我真的失去了下一步該做什麼。我沒有收到任何錯誤,但沒有音頻。AVAudioPlayer不播放MP3文件

@IBAction func play (sender: AnyObject){ 

func sharedInstance() { 
     AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil) 
     AVAudioSession.sharedInstance().setActive(true, error: nil) 

     var audioPlayer = AVAudioPlayer() 
     var song = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("pingpong", ofType: "mp3")!) 
     println(song) 



     var error:NSError? 
     audioPlayer = AVAudioPlayer(contentsOfURL: song, error: &error) 
     audioPlayer.prepareToPlay() 
     audioPlayer.play() 
} 
sharedInstance() 

} 
+0

檢查您的手機是否處於靜音模式。 – DHEERAJ

+0

手機確實沒有處於靜音模式。 – Matt

回答

1

只是讓你var audioPlayer = AVAudioPlayer()全球對你的類在下面的代碼所示,如​​:

我修改了代碼,使其安全:

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    var audioPlayer = AVAudioPlayer() 

    @IBAction func play (sender: AnyObject){ 

     var categoryError: NSError? 
     if AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &categoryError) { 
      println("AVAudioSession Category Playback OK") 
      var activateError: NSError? 
      if AVAudioSession.sharedInstance().setActive(true, error: &activateError) { 
       println("AVAudioSession is Active") 
       var song = NSBundle.mainBundle().URLForResource("we_cant_Stop", withExtension: "mp3")! 
       var error:NSError? 
       audioPlayer = AVAudioPlayer(contentsOfURL: song, error: &error) 
       audioPlayer.play() 

      } else if let activateError = activateError { 
       println(activateError.description) 
      } 
     } else if let categoryError = categoryError { 
      println(categoryError.description) 
     } 
    } 
} 

這是工作的罰款。