Debian Codegraph @

plyer/platforms/macosx/audio.py

raw symbols SCIP
1 from os.path import join
2
3 from pyobjus import autoclass
4 from pyobjus.dylib_manager import INCLUDE, load_framework
5
6 from plyer.facades import Audio
7 from plyer.platforms.macosx.storagepath import OSXStoragePath
8
9 load_framework(INCLUDE.Foundation)
10 load_framework(INCLUDE.AVFoundation)
11
12 AVAudioPlayer = autoclass("AVAudioPlayer")
13 AVAudioRecorder = autoclass("AVAudioRecorder")
14 AVAudioFormat = autoclass("AVAudioFormat")
15 NSString = autoclass('NSString')
16 NSURL = autoclass('NSURL')
17 NSError = autoclass('NSError').alloc()
18
19
20 class OSXAudio(Audio):
21 def __init__(self, file_path=None):
22 default_path = join(
23 OSXStoragePath().get_music_dir(),
24 'audio.wav'
25 )
26 super().__init__(file_path or default_path)
27
28 self._recorder = None
29 self._player = None
30 self._current_file = None
31
32 def _start(self):
33 # Conversion of Python file path string to Objective-C NSString
34 file_path_NSString = NSString.alloc()
35 file_path_NSString = file_path_NSString.initWithUTF8String_(
36 self._file_path
37 )
38
39 # Definition of Objective-C NSURL object for the output record file
40 # specified by NSString file path
41 file_NSURL = NSURL.alloc()
42 file_NSURL = file_NSURL.initWithString_(file_path_NSString)
43
44 # Internal audio file format specification
45 af = AVAudioFormat.alloc()
46 af = af.initWithCommonFormat_sampleRate_channels_interleaved_(
47 1, 44100.0, 2, True
48 )
49
50 # Audio recorder instance initialization with specified file NSURL
51 # and audio file format
52 self._recorder = AVAudioRecorder.alloc()
53 self._recorder = self._recorder.initWithURL_format_error_(
54 file_NSURL, af, NSError
55 )
56
57 if not self._recorder:
58 raise Exception(NSError.code, NSError.domain)
59
60 self._recorder.record()
61
62 # Setting the currently recorded file as current file
63 # for using it as a parameter in audio player
64 self._current_file = file_NSURL
65
66 def _stop(self):
67 if self._recorder:
68 self._recorder.stop()
69 self._recorder = None
70
71 if self._player:
72 self._player.stop()
73 self._player = None
74
75 def _play(self):
76 # Audio player instance initialization with the file NSURL
77 # of the last recorded audio file
78 self._player = AVAudioPlayer.alloc()
79 self._player = self._player.initWithContentsOfURL_error_(
80 self._current_file, NSError
81 )
82
83 if not self._player:
84 raise Exception(NSError.code, NSError.domain)
85
86 self._player.play()
87
88
89 def instance():
90 return OSXAudio()