Merge: nitc: check pkg-config packages availability later
[nit.git] / lib / ios / audio.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 # iOS implementation of `app::audio` using `AVAudioPlayer`
16 module audio
17
18 import app::audio
19 intrude import ios::assets
20
21 in "ObjC Header" `{
22 #import <AVFoundation/AVFoundation.h>
23 `}
24
25 redef class PlayableAudio
26
27 redef var error = null
28
29 private var native: nullable AVAudioPlayer is lazy do
30
31 # Find file
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")
36 return null
37 end
38
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")
43 return null
44 end
45
46 player.prepare_to_play
47
48 return player
49 end
50
51 redef fun load do native # For lazy loading
52
53 redef fun play
54 do
55 var native = native
56 if native != null then native.play_and_repare_async
57 end
58
59 # Free native resources
60 fun destroy
61 do
62 var native = native
63 if native != null then native.release
64 end
65 end
66
67 # Audio player playing audio from a file or from memory
68 private extern class AVAudioPlayer in "ObjC" `{ AVAudioPlayer *`}
69 super NSObject
70
71 new contents_of(url: NSObject) in "ObjC" `{
72 NSError *error;
73 AVAudioPlayer *a = [[AVAudioPlayer alloc] initWithContentsOfURL:(NSURL*)url error:&error];
74 if (error != nil) {
75 NSLog(@"Failed to load sound: %@", [error localizedDescription]);
76 return NULL;
77 }
78
79 return (__bridge AVAudioPlayer*)CFBridgingRetain(a);
80 `}
81
82 fun play in "ObjC" `{ [self play]; `}
83
84 fun prepare_to_play in "ObjC" `{ [self prepareToPlay]; `}
85
86 fun play_and_repare_async in "ObjC" `{
87 dispatch_queue_t q = dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0);
88 dispatch_async(q, ^{
89 [self play];
90 [self prepareToPlay];
91 });
92 `}
93
94 fun release in "ObjC" `{ CFBridgingRelease((__bridge void*)self); `}
95 end