2015-03-02 107 views

回答

3

通過使用WatchKit API無法播放任何音頻。

+1

Jordi是正確的,這對於當前的WatchKit實現來說是不可能的。您只能播放iOS應用中的音頻。 – cnoon 2015-03-03 16:43:22

0

在watchOS 2中,現在可以實現了。由於NDA,我不能詳細說明。請查閱Apple提供的開發者文檔。

0

您可以加載音頻文件或系統聲音,並使用Apple Watch揚聲器播放。使用WKAudioFilePlayer用於播放音頻文件所需的藍牙耳機連接到Apple Watch以播放聲音。

播放任何爲數不多的觸覺反饋使用振動WKInterfaceDevice聲音:

[[WKInterfaceDevice currentDevice] playHaptic:WKHapticTypeFailure] 

要播放任何音頻文件,使用AVAudioEngine

1)添加AVFoundation.framework到您的框架列表。

2)在h文件,把

#import <AVFoundation/AVFoundation.h> 

@property (nonatomic) AVAudioEngine *audioEngine; 
@property (nonatomic) AVAudioPlayerNode *playerNode; 
@property (nonatomic) AVAudioFile *audioFile; 
@property (nonatomic) AVAudioPCMBuffer *audioPCMBuffer; 

3).m文件,把

NSError *error = nil; 
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"alarm" withExtension:@"wav"]; 
self.audioFile = [[AVAudioFile alloc] initForReading:fileURL error:&error]; 
if (error) { 
    NSLog(@"error"); 
    return; 
} 

self.audioEngine = [[AVAudioEngine alloc]init]; 

AVAudioFormat *audioFormat = self.audioFile.processingFormat; 
AVAudioFrameCount length = (AVAudioFrameCount)self.audioFile.length; 
self.audioPCMBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:audioFormat frameCapacity:length]; 
[self.audioFile readIntoBuffer:self.audioPCMBuffer error:nil]; 


AVAudioMixerNode *mixerNode = [self.audioEngine mainMixerNode]; 
self.playerNode = [[AVAudioPlayerNode alloc] init]; 
[self.audioEngine attachNode:self.playerNode]; 
[self.audioEngine connect:self.playerNode to:mixerNode format:self.audioFile.processingFormat]; 

[self.audioEngine startAndReturnError:&error]; 
[self.playerNode scheduleFile:self.audioFile atTime:nil completionHandler:nil]; 
[self.playerNode play]; 

可以使用這些類從watchOS 2.0進一步。有一個playHaptic:AVAudioEngine類的文檔。

我希望這會幫助你解決你的問題。