Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I play a custom sound in WatchOS 3 that will playback on the watch speakers

I've read that we can now play custom sounds on the apple watch in watchos 3.

According to the announcement from Apple so apparently there is but I don't have an example to test it out: 3D spatial audio implemented using SCNAudioSource or SCNAudioPlayer. Instead, use playAudioSource:waitForCompletion: or the WatchKit sound or haptic APIs. Found here: https://developer.apple.com/library/prerelease/content/releasenotes/General/WhatsNewInwatchOS/Articles/watchOS3.html

Can someone place a simple example of this. I'm not using SceneKit in my app as I don't need it but if that's the only way to play a custom sound then I'd like to know the minimum code required to accomplish this. Preferably in Objective c but I'll take it in whatever shape. I'm ok using SpriteKit if that's easier also.

Here's what I have so far but it doesn't work:

SCNNode * audioNode = [[SCNNode alloc] init];

SCNAudioSource * audioSource = [SCNAudioSource audioSourceNamed:@"mysound.mp3"];
SCNAudioPlayer * audioPlayer = [SCNAudioPlayer audioPlayerWithSource:audioSource];  
[audioNode addAudioPlayer:audioPlayer];

SCNAction * play = [SCNAction playAudioSource:audioSource waitForCompletion:YES];
[audioNode runAction:play];
like image 466
Saviz Avatar asked Dec 10 '22 15:12

Saviz


1 Answers

I can confirm, that @ApperleyA solution really works!

Here is the swift version:

var _audioPlayer : AVAudioPlayerNode!
var _audioEngine : AVAudioEngine!

func playAudio()
{
    if (_audioPlayer==nil) {
        _audioPlayer = AVAudioPlayerNode()
        _audioEngine = AVAudioEngine()
        _audioEngine.attach(_audioPlayer)

        let stereoFormat = AVAudioFormat(standardFormatWithSampleRate: 44100, channels: 2)
        _audioEngine.connect(_audioPlayer, to: _audioEngine.mainMixerNode, format: stereoFormat)

        do {

            if !_audioEngine.isRunning {
                try _audioEngine.start()
            }

        } catch {}

    }


    if let path = Bundle.main.path(forResource: "test", ofType: "mp3") {

        let fileUrl = URL(fileURLWithPath: path)

        do {
            let asset = try AVAudioFile(forReading: fileUrl)

            _audioPlayer.scheduleFile(asset, at: nil, completionHandler: nil)
            _audioPlayer.play()

        } catch {
            print ("asset error")
        }

    }


}
like image 177
dunqan Avatar answered Dec 13 '22 03:12

dunqan