Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ios - Playing sound in Apple Watchkit

I'm trying to play a sound through the watchkit extension using WKAudioFilePlayer however no sound gets played. I'm using the haptic feedback code as a sort of debug to be sure it executes it (which it does). As a side note, mute is not on and the filename is correct.

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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I implemented as follows and it worked fine. (Sorry, it's Swift)

1) Define a property for the player object

var player: WKAudioFilePlayer!

2) Setup the asset and player when it's awaking

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) Play if the player is ready to play.

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

In addition, it needed to connect a Bluetooth Headset with ?watch.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...