2016-10-11 181 views
-2

我有一个简单的程序,它有一个按钮,它的唯一功能是触发声音输出。Swift 3 - AVAudioPlayer不播放声音

该应用在iOS模拟器上测试时效果很好,但是当我在iPhone上测试时,该应用没有播放任何声音。我已经在两款iPhone上测试过了。

这是曾经的工作。我不知道是否更新到iOS 10导致了这个问题。

这里是我的代码:

//Code 
import UIKit 
import AVFoundation 

var audioPlayer = AVAudioPlayer() 


class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 


     let music = Bundle.main.path(forResource: "sound", ofType: "wav") 

     do { 
      audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music!)) 
     } 
     catch{ 
      print(error) 
     } 

    } 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    @IBAction func playSound(_ sender: UIButton) { 

     audioPlayer.play() 
    } 

} 

将是任何答案感谢。 谢谢。

+1

请检查iPhone手机的您的音量级别(不铃声) – Alex

回答

0
override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 


     let music = Bundle.main.path(forResource: "sound", ofType: "wav") 

     do { 
      audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music!)) 
audioPlayer.delegate = self 
audioPlayer.preparedToPlay() 
     } 
     catch{ 
      print(error) 
     } 

    } 
0
import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

var btnSound: AVAudioPlayer! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    //locate resource 
    let path = Bundle.main.path(forResource: "sound", ofType: "wav") 
    let music = URL(fileURLWithPath: path!) 

    do{ 
     try btnSound = AVAudioPlayer(contentsOf: music) 
     btnSound.prepareToPlay() 
    } catch let err as NSError{ 
     print(err.debugDescription) 
    } 
} 
} 

func playSound(){ 
    if btnSound.isPlaying{ 
     //stop playing sound file if already playing 
     btnSound.stop() 
    } 
    //play sound 
    btnSound.play() 
} 

@IBAction func playSound(sender: UIButton){ 
    //call playSound function on pressing the button you attach this function to 
    playSound() 
} 
+0

请说明您的代码 –