AVAudioPlayer无法播放声音 [英] AVAudioPlayer not playing sound

查看:215
本文介绍了AVAudioPlayer无法播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WatchKit应用程序,当在手表上轻按一个按钮时,它会发出信号,通知iOS应用程序播放声音.出于某种原因,当我使用自定义类处理AVAudioPlayer实例并播放声音时,声音无法播放.如果我在session:didReceiveMessage:replyHandler:中执行该操作,则效果很好.

I have a WatchKit app that when a button is tapped on the watch it signals the iOS app to play a sound. For some reason, the sound isn't playing when I use a custom class to handle setting up an instance of AVAudioPlayer and playing the sound. If I do that part within session:didReceiveMessage:replyHandler: it plays fine.

这是自定义类:

import AVFoundation

class ChildClass {
    let mySound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("test", ofType: "wav")!)
    var audioPlayer: AVAudioPlayer!

    func playSound() {
        do {
            print("Playing sound")
            self.audioPlayer = try AVAudioPlayer(contentsOfURL: mySound)
            self.audioPlayer.play()
        } catch {
            print("Error getting audio file")
        }
    }
}

在我的ViewController中实例化了一个

Which is instantiated in my ViewController :

class ViewController: UIViewController, WCSessionDelegate {
    var session: WCSession!

    override func viewDidLoad() {
        super.viewDidLoad()

        if WCSession.isSupported() {
            session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()
        }
    }

    func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
        let mySounds = ChildClass()
        mySounds.playSound()
    }
}

ChildClass.playSound()中设置断点我可以确认它正在被调用.但是不仅声音不会播放,而且print()似乎也无法在控制台上打印任何内容.

Setting up breakpoints in ChildClass.playSound() I can confirm that it is getting called. But not only doesn't the sound play but the print() doesn't appear to print anything to the console either.

AVAudioPlayer实例是否存在于自定义类中,导致它无法播放声音?或者,也许由于某些原因,iOS应用程序无法播放音频?

Is there something about the AVAudioPlayer instance being in a custom class causing it to not play the sound? Or, perhaps the audio isn't being played by the iOS app for some reason?

推荐答案

在播放声音之前,"mySounds"超出范围. 将其设置为实例变量,然后看看会发生什么.

Your "mySounds" goes out of scope before the sound can play. Make it an instance variable and see what happens.

这篇关于AVAudioPlayer无法播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆