2016-03-15 35 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() 
    }