2011-11-16 45 views
2


我目前使用CocosDenshion的小音效(半秒鐘),現在 我需要播放短的30秒音頻剪輯(MP3),是託管在服務器上,不在應用程序資源包內。我試圖獲得一些代碼來播放它與兩個「要求」:播放遠程MP3文件與緩衝/流塊

  1. 它播放時,因爲它加載,所以我不會等待整個事情加載只是爲了播放它。
  2. 它會有某種委託來顯示播放曲目的進度。

我試過使用AVAudioPlayer,但它不適用於我,再加上它沒有「緩衝」數據,它等待加載整個事件(如果它在模擬器上試驗)。我的嘗試是:

- (IBAction)play:(id)sender{ 
    NSString *_mp3file = @"http://www.somesite.com/somefile.mp3"; 
    NSData *_mp3data = [NSData dataWithContentsOfURL:[NSURL URLWithString: _mp3file]]; 

    NSError *error; 

    AVAudioPlayer *avp = [[AVAudioPlayer alloc] initWithData:_mp3data error:&error]; 
    avp.numberOfLoops = 0; 
    avp.volume = 1.0f; 
    avp.delegate = self; 
    [avp prepareToPlay]; 

    if(avp == nil) 
     GTMLoggerError(@"%@", error); 
    else 
     [avp play]; 
} 

會愛你的幫助的經歷對這個:)
乾杯,
夏嘉曦。

+2

你可以試試[這](http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html) –

+0

看起來不錯, 謝謝 ! :) –

回答

1

在你didLoad方法

dispatch_queue_t dispatchQueue = 
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
dispatch_async(dispatchQueue, ^(void){ 
    NSString *_mp3file = @"http://cs4405.vk.me/u360087/audios/4efe178f2608.mp3"; 
    NSData *_mp3Data = [NSData dataWithContentsOfURL:[NSURL URLWithString: _mp3file]]; 
    NSError *_error = nil; 

    self._audioPlayer = [[AVAudioPlayer alloc] initWithData:_mp3Data error:&_error]; 

    if (self._audioPlayer != nil) 
    { 
     self._audioPlayer.delegate = self; 
     if ([self._audioPlayer prepareToPlay] && [self._audioPlayer play]) 
     { 
      NSLog(@"Successfully started playing"); 
     } else { 
      NSLog(@"Failed to play"); 
     } 
    } else { 
     NSLog(@"Failed to instanciate player"); 
    } 
}); 
+0

我實際上使用了Tushar的解決方案(在上面的評論中),不過謝謝! –