1111#import " LView.h"
1212#import " LVHeads.h"
1313
14- @interface LVAudioPlayer ()
14+ @interface LVAudioPlayer ()<AVAudioPlayerDelegate>
1515
1616@property (nonatomic ,assign ) BOOL playing;
1717@property (nonatomic , copy ) NSString *fileName;
@@ -52,29 +52,33 @@ -(void) setPlayFileName0:(NSString*) fileName bundle:(LVBundle*) bundle{
5252 if ( path ) {
5353 NSURL * url = [[NSURL alloc ] initWithString: path];
5454 NSError * error = nil ;
55+ [self stop ];
5556 audioPlayer = [[AVAudioPlayer alloc ] initWithContentsOfURL: url error: &error];// 使用本地URL创建
57+ audioPlayer.delegate = self;
58+
5659 if ( error ) {
5760 NSLog (@" [LuaView][error]%@ " ,error);
5861 }else {
5962 self.fileName = fileName;
6063 }
6164 }
62- if ( !self.playing ) {
63- [self play ];
64- }
65+
66+ [self play ];
6567}
6668
6769-(void ) setPlayFileName : (NSString *) fileName bundle : (LVBundle*) bundle {
6870 if ( fileName ==nil )
6971 return ;
7072 if ( [LVUtil isExternalUrl: fileName] ){
73+
74+ __weak typeof (self) wself = self;
7175 [LVUtil download: fileName callback: ^(NSData *fileData) {
7276 NSString * suffix = [fileName componentsSeparatedByString: @" ." ].lastObject ;
7377 NSData * theFileNameData = [fileName dataUsingEncoding: NSUTF8StringEncoding];
7478 NSString * md5Path = [LVUtil MD5HashFromData: theFileNameData];
7579 md5Path = [NSString stringWithFormat: @" %@ .%@ " ,md5Path,suffix];// Mp3文件一定要加后缀,否则无法播放
7680 if ( [LVUtil saveData: fileData toFile: [LVUtil PathForCachesResource: md5Path]] ) {
77- [self setPlayFileName0: md5Path bundle: bundle];
81+ [wself setPlayFileName0: md5Path bundle: bundle];
7882 }
7983 }];
8084 } else {
@@ -83,20 +87,25 @@ -(void) setPlayFileName:(NSString*) fileName bundle:(LVBundle*) bundle{
8387}
8488
8589-(void ) play {
86- [audioPlayer play ];
87- self.playing = YES ;
90+ if (!self.playing ){
91+ [audioPlayer play ];
92+ self.playing = YES ;
93+ }
8894}
8995
9096-(void ) stop {
9197 [audioPlayer stop ];
9298 self.playing = NO ;
9399}
94100
101+ - (void )audioPlayerDidFinishPlaying : (AVAudioPlayer *)player successfully : (BOOL )flag {
102+ self.playing = NO ;
103+ }
104+
95105- (id ) lv_nativeObject {
96106 return audioPlayer;
97107}
98108
99-
100109#pragma -mark AudioPlayer
101110
102111static int lvNewAudioPlayer (lua_State *L) {
@@ -133,9 +142,7 @@ static int play (lua_State *L) {
133142 NSString * fileName = lv_paramString (L, 2 );
134143
135144 if (![player.fileName isEqualToString: fileName]){
136- if (player.playing ){
137- [player stop ];
138- }
145+ [player stop ];
139146 LuaViewCore* lview = LV_LUASTATE_VIEW (L);
140147 [player setPlayFileName: fileName bundle: lview.bundle];
141148 }
0 commit comments