2015-06-25 169 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) 
     } 
    } 
} 

这是工作的罚款。