1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # iOS implementation of `app::audio` using `AVAudioPlayer`
19 intrude import ios
::assets
22 #import <AVFoundation/AVFoundation.h>
25 redef class PlayableAudio
27 redef var error
= null
29 private var native
: nullable AVAudioPlayer is lazy
do
32 var ns_path
= ("assets"/path
).to_nsstring
33 var url_in_bundle
= asset_url
(ns_path
)
34 if url_in_bundle
.address_is_null
then
35 self.error
= new Error("Sound at '{path}' not found")
39 var player
= new AVAudioPlayer.contents_of
(url_in_bundle
)
40 # TODO set delegate to get further errors
41 if player
.address_is_null
then
42 self.error
= new Error("Sound at '{path}' failed to load")
46 player
.prepare_to_play
51 redef fun load
do native
# For lazy loading
56 if native
!= null then native
.play_and_repare_async
59 # Free native resources
63 if native
!= null then native
.release
67 # Audio player playing audio from a file or from memory
68 private extern class AVAudioPlayer in "ObjC" `{ AVAudioPlayer *`}
71 new contents_of(url: NSObject) in "ObjC" `{
73 AVAudioPlayer *a
= [[AVAudioPlayer alloc
] initWithContentsOfURL
:(NSURL*)url error
:&error
];
75 NSLog(@
"Failed to load sound: %@", [error localizedDescription
]);
79 return (__bridge
AVAudioPlayer*)CFBridgingRetain(a
);
82 fun play in "ObjC" `{ [self play]; `}
84 fun prepare_to_play
in "ObjC" `{ [self prepareToPlay]; `}
86 fun play_and_repare_async in "ObjC" `{
87 dispatch_queue_t q
= dispatch_get_global_queue
(QOS_CLASS_USER_INTERACTIVE, 0);
94 fun release in "ObjC" `{ CFBridgingRelease((__bridge void*)self); `}