音频播放器不播放音乐

时间:2016-01-27 05:50:20

标签: ios swift cocoa-touch avfoundation

我尝试使用下面的代码来播放音频,我调试并发现soundURL有效,print语句打印了一些对象的内存地址,表明对象已实例化,但仍然没有声音,任何想法?感谢。

func kkTableView(tableView: UITableView, selectIndex indexPath: NSIndexPath) {
    let audioPlayer = generateAudioPlayerWithName(tickSounds![indexPath.row])
    print("\(audioPlayer)")
    audioPlayer.play()
}

func generateAudioPlayerWithName(name: String) -> AVAudioPlayer {
    let soundURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(name, ofType: "wav")!)
    var audioPlayer: AVAudioPlayer
    do {
        try audioPlayer = AVAudioPlayer(contentsOfURL: soundURL)
        audioPlayer.numberOfLoops = -1
        return audioPlayer
    } catch {
        fatalError("\(error)")
    }
}

2 个答案:

答案 0 :(得分:1)

全局初始化audioPlayer,然后将其实例化以使用声音播放。有关详细信息,请查看https://www.youtube.com/watch?v=vcs0BuDw9BA以播放音频。

答案 1 :(得分:1)

我不知道您在哪里声明name用于文件名,但我会假设您给它一个有效的String,导致现有文件。以下代码示例将成功使用AVAudioPlayer播放音频,您可以根据自己的需要进行调整...

    var AudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Besides", ofType: "mp3")!)
    var AudioPlayer = AVAudioPlayer()

   override func viewDidLoad() {
   super.viewDidLoad()

   do {
    try AudioPlayer  = AVAudioPlayer(contentsOfURL: AudioURL, fileTypeHint: nil)
   } catch {
    print("errorin do-try-catch")
   }

}

 @IBAction func(){
    AudioPlayer.play()
}

您需要对AVAudioPlayer保持强烈的引用。一旦它离开它的方法就会被解除分配

相关问题