2016-01-05 63 views
0

在這裏,我正在重新加載mpeg文件,每次播放一段。如何有效地解析mpeg文件?

我寧願逐步通過一個加載的文件,但我似乎無法建立一個定位一致的文件指針......以下方法是我能做的最好的。

我錯過了什麼有效地只通過一個文件? THX

float offset[26] = { 2.1, 3.1, 4.0, 5.0, 5.5, 
         6.5, 7.8, 8.8, 10.0, 10.7, 
        11.5, 12.5, 13.5, 14.5, 15.3, 
        16.1, 17.2, 17.9, 18.9, 19.7, 
        20.5, 21.5, 22.5, 23.5, 24.5, 25.3 }; //fileOffset for voice segments 


for (int i = 25; i > -1 ; i--) { 
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
    player.numberOfLoops = 0; 

    [player playAtTime: player.deviceCurrentTime - offset[i]]; 

    sleep(1);//one second duration 
    [player stop]; 
} 

回答

1

你可以利用- audioPlayerDidFinishPlaying:successfully:AVAudioPlayerDelegate方法,找出當片段播放完畢,然後再尋求下一個位置,避免了需要重建的變量,每次重新加載音頻文件。

@property (nonatomic) float indexOfLastOffset; 
@property (nonatomic) float offsets[16]; 

- (void)viewDidLoad:(BOOL)animated { 
    self.indexOfLastOffset = 25; 
    self.offsets = { 2.1, 3.1, 4.0, 5.0, 5.5, 
        6.5, 7.8, 8.8, 10.0, 10.7, 
       11.5, 12.5, 13.5, 14.5, 15.3, 
       16.1, 17.2, 17.9, 18.9, 19.7, 
       20.5, 21.5, 22.5, 23.5, 24.5, 25.3 }; 

    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
    player.numberOfLoops = 0; 
    player.delegate = self; 
    [self player:player playWithOffsetIndex:self.indexOfLastOffset]; 

    [super viewDidLoad]; 
} 

- (void)player:(AVAudioPlayer *)player playWithOffsetIndex:(NSUInteger)offsetIdx { 
    [player playAtTime:player.deviceCurrentTime - offsets[offsetIdx]]; 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player 
         successfully:(BOOL)flag { 
    if (flag && indexOfLastOffset >= 0) { 
     [self player:player playWithOffsetIdx:self.indexOfLastOffset - 1]; 
     self.indexOfLastOffset -= 1; 
    } 
    else { 
     [player stop]; 
    } 
}