有没有办法从Apple Watch的扬声器中播放声音?我无法在线找到任何文档。
现在可以使用WKAudioFilePlayer
或WKInterfaceMovie
从watchOS 2开始。
NSURL *assetURL = [[NSBundle mainBundle] URLForResource:@"file" withExtension:@"wav"];
WKAudioFilePlayer
例子:
WKAudioFileAsset *asset = [WKAudioFileAsset assetWithURL:assetURL];
WKAudioFilePlayerItem *playerItem = [WKAudioFilePlayerItem playerItemWithAsset:asset];
WKAudioFilePlayer *audioFilePlayer = [WKAudioFilePlayer playerWithPlayerItem:playerItem];
[audioFilePlayer play];
WKInterfaceMovie
例子:
[self presentMediaPlayerControllerWithURL:assetURL options:nil completion:nil];
无法从Apple Watch的扬声器中播放声音,但您可以触发在iPhone上播放声音文件,这里是关于它的thread
URL您要播放的媒体文件的URL。 URL必须指定一个文件;不支持流媒体。该文件可能包含音频,视频或两者。
如果为远程服务器上的文件指定URL,则此方法首先下载文件并显示显示操作进度的进度指示器。由于WatchKit在从Web服务器下载文件时使用App Transport Security(ATS),因此该文件必须位于安全服务器上,并且URL必须使用https方案。如果您的服务器不支持ATS级别的安全性,请在播放之前自行下载该文件。
使用sharedcontainer,watch extensions来存储文件。
使用此方法播放的任何音频都会路由到配对的蓝牙音频设备(如果有)。如果没有可用的蓝牙音频设备,音频将路由到Apple Watch扬声器。
对于WatchOS3,原始问题的答案是WKInterfaceInlineMovie https://developer.apple.com/reference/watchkit/wkinterfaceinlinemovie
您可以隐藏窗口小部件,使其不会改变您的界面设计。如果没有连接蓝牙音箱,它会通过手表的扬声器播放音频文件。
import AVFoundation
var player: AVAudioPlayer?
if let path = Bundle.main.path(forResource: "siren", ofType: "wav") {
let fileUrl = URL(fileURLWithPath: path)
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: fileUrl)
guard let player = player else { return }
player.play()
}
catch
{
}
}
我用这个来播放苹果手表(4.3)扬声器的自定义声音,工作得很好。不要忘记将音频文件目标成员资格设置为监视工具包。
在模拟器和设备中运行良好也可在最新的WatchOS 5中使用
import AVFoundation
var player = AVAudioPlayer()
let audioSession = AVAudioSession.sharedInstance()
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
do {
// Working Reroutes to headset
// try session.setCategory(AVAudioSession.Category.playback,
// mode: .default,
// policy: .longForm,
// options: [])
// Plays in watch speaker
try audioSession.setCategory(AVAudioSession.Category.playback,
mode: .default,
policy: .default,
options: [])
} catch let error {
fatalError("*** Unable to set up the audio session: \(error.localizedDescription) ***")
}
if let path = Bundle.main.url(forResource: "piano", withExtension: "mp3") {
let fileUrl = path
do{
player = try AVAudioPlayer(contentsOf: fileUrl)
}
catch
{
print("*** Unable to set up the audio player: \(error.localizedDescription) ***")
// Handle the error here.
return
}
}
}
使用此代码调用音频会话并在播放按钮操作内或在您希望音频播放的任何情况下播放音频。
audioSession.activate(options: []) { (success, error) in
guard error == nil else {
print("*** error occurred: \(error!.localizedDescription)
***")
// Handle the error here.
return
}
if(success){
// Play the audio file.
self.player.play()
}
}
如果您仍然无法播放音频,那一定是因为您在音频文件中获得了nil值,指定的音频文件将不在您要搜索的右侧包中