在 Apple Watchkit 中播放声音

Playing sound in Apple Watchkit

我正在尝试使用 WKAudioFilePlayer 通过 watchkit 扩展播放声音,但是没有播放任何声音。我正在使用触觉反馈代码作为一种调试,以确保它执行它(它确实执行了)。作为旁注,静音未打开且文件名正确。

NSURL *falcon = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                        pathForResource:@"falcon"
                                        ofType:@"mp3"]];
WKAudioFileAsset *asset = [WKAudioFileAsset assetWithURL:falcon];
WKAudioFilePlayerItem *sound = [WKAudioFilePlayerItem playerItemWithAsset:asset];
audioPlayer = [WKAudioFilePlayer playerWithPlayerItem:sound];


[audioPlayer play];

WKInterfaceDevice *device = [WKInterfaceDevice currentDevice];
[device playHaptic:WKHapticTypeClick];

我按如下方式实现,效果很好。 (抱歉,是 Swift)

1) 为玩家对象定义一个属性

var player: WKAudioFilePlayer!

2) 唤醒时设置资产和播放器

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    let filePath = NSBundle.mainBundle().pathForResource("se_tap", ofType: "m4a")!
    let fileUrl = NSURL.fileURLWithPath(filePath)
    let asset = WKAudioFileAsset(URL: fileUrl)
    let playerItem = WKAudioFilePlayerItem(asset: asset)
    player = WKAudioFilePlayer(playerItem: playerItem)
}

3) 如果玩家准备好玩就玩

@IBAction func playBtnTapped() {
    switch player.status {
    case .ReadyToPlay:
        player.play()
    case .Failed:
        print("failed")
    case .Unknown:
        print("unknown")
    }
}

此外,需要连接一个蓝牙耳机和watch。