如何在服务器上远程播放mp3文件而不阻止ios中的UI

时间:2015-01-21 06:15:01

标签: xcode url ios8 avaudioplayer

我在iOS应用程序上工作让我从url播放mp3文件。一旦加载就可以正常工作。问题是加载并阻止UI从转换到其他视图控制器大约需要30秒。 代码:

我正在使用AVAudioPlayer类,这是我的设置。

(void)setupAudioPlayer:(NSString*)fName
{

         // calls and pass url name to MyAudioPlayer class method
         [self.audioPlayer initWithData:fName];
         self.currentTimeSlider.maximumValue = 
         [self.audioPlayer getAudioDuration];

         //init the current time display and the labels.
         //if a current time was stored
        //for this player then take it and update the time display
        self.timeElapsed.text = @"0:00";

        self.duration.text = [NSString stringWithFormat:@"-%@",
                          [self.audioPlayer timeFormat:
                         [self.audioPlayer  getAudioDuration]]];

}
    (void)viewDidLoad
    {
        [super viewDidLoad];
        self.audioPlayer = [[MyAudioPlayer alloc] init];
        //pass the url where mp3 located i.e http://www.test.com/test.mp3
        [self setupAudioPlayer:self.urlStr];
    }

然后,当按下按钮时播放。

- (IBAction)playAudioPressed:(id)playButton
 {
     [self.timer invalidate];

     //play audio for the first time or if pause was pressed
     if (!self.isPaused) {

        //start a timer to update the time label display
        self.timer = 
        [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(updateTimer:)
                                       userInfo:nil
                                        repeats:YES];

         [self.audioPlayer playAudio];
         self.isPaused = TRUE;

     } else {
          [self.audioPlayer pauseAudio];
          self.isPaused = FALSE;
    }
}

正如我前面提到的,问题是加载非常长并阻塞UI。请帮助或建议我如何减少加载时间,避免阻止ui。

任何帮助都将非常感激。

谢谢

1 个答案:

答案 0 :(得分:0)

这是我的远程mp3文件STREAMING的代码:

@import AVFoundation;
...

@property (nonatomic, retain) AVPlayer *objAVPlayer;
@property (nonatomic, getter=isPlaying) BOOL playing;

// in viewDidLoad
_objAVPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:@"http://www.asdasd.com/file.mp3"]];

...

- (void)playPressed {
    if([self isPlaying]) {
        _playing = false;
        [_objAVPlayer pause];
    } else {
        _playing = true;
        [_objAVPlayer play];
    }
}

可能的延迟可能是由于连接速度慢造成的。我希望这可以帮到你。