更改AVAudio流中的曲目

时间:2014-09-09 11:04:31

标签: objective-c ios7 avfoundation

我有一个程序,它使用分段控件来使用AVFoundation音频功能控制音频流。然而,它看起来非常混乱,我每次想要改变音乐曲目时都必须重新实例化它。

我怎样才能让它更加优雅和干净?我是否真的需要为每个播放新曲目的实例创建一个新播放器?

- (IBAction)musicChoice:(UISegmentedControl *)segmentedControl {
    switch(segmentedControl.selectedSegmentIndex)
    {
        { case 0:
            [self.player pause];

             currentMusic = arc4random_uniform(upperBound);

            NSString *soundFilePath =
            [[NSBundle mainBundle] pathForResource: _musicToPlay[currentMusic]
                                            ofType: @"mp3"];
            NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

            AVAudioPlayer *newPlayer =
            [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                   error: nil];

            self.player = newPlayer;

            [_player prepareToPlay];
            [_player setDelegate: self];

            [self.player play];
            break; }
        { case 1:
            [self.player pause];

            NSString *soundFilePath =
            [[NSBundle mainBundle] pathForResource: @"Track1"
                                            ofType: @"mp3"];
            NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

            AVAudioPlayer *newPlayer =
            [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                   error: nil];

            self.player = newPlayer;

            [_player prepareToPlay];
            [_player setDelegate: self];

            [self.player play];
            break; }
        { case 2:
            [self.player pause];

            NSString *soundFilePath =
            [[NSBundle mainBundle] pathForResource: @"Track2"
                                            ofType: @"mp3"];
            NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

            AVAudioPlayer *newPlayer =
            [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                   error: nil];

            self.player = newPlayer;

            [_player prepareToPlay];
            [_player setDelegate: self];

            [self.player play];
            break; }
    }
}

这是我用来循环音乐曲目的NSArray。

_musicToPlay = @[@"Track1",@"Track2",@"Track3",@"Track4",@"Track5"];

到达此IBAction时,我已经播放了音乐,这就是我使用

的原因
[self.player pause];

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试使用AVQueuePlayer,如果您事先知道某些流,则可能会混淆播放列表顺序以更改下一个播放的文件。

否则,如果您需要在流之间缩短停机时间,则可以尝试使用较低级别的框架,例如AudioQueue或CoreAudio的AudioUnits