2012-08-11 94 views
2

我嘗試了以下三種解決方案,但都沒有工作。我相信我錯過了一些關鍵點,但不清楚是什麼。 (僅供參考,我在iPhone設備上嘗試以下解決方案,而不是在模擬器。)從網絡播放mp3

- (IBAction)actionAVPlayer:(id)sender { 
AVPlayer* player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:urlTextField.text]]; 
[player play]; 

} 

- (IBAction)actionMemoryBuffer1:(id)sender { 

    NSError *error; 
    NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlTextField.text]]; 

    AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error]; 
    audioPlayer.numberOfLoops = -1; 
    audioPlayer.delegate = self; 
    audioPlayer.volume = 1.0f; 
    [audioPlayer prepareToPlay]; 

    if (audioPlayer == nil) 
    NSLog(@"%@", [error description]); 
    else 
    [audioPlayer play]; 
} 


- (IBAction)actionMemoryBuffer2:(id)sender { 

    NSURLRequest* request = [ NSURLRequest requestWithURL: [NSURL URLWithString:urlTextField.text] ]; 
    NSError *requestError; 
    NSURLResponse *urlResponse = nil; 

    NSData *_objectData = [ NSURLConnection sendSynchronousRequest:request returningResponse: &urlResponse error: &requestError]; 

    NSError *error; 
    AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error]; 
    audioPlayer.numberOfLoops = -1; 
    audioPlayer.delegate = self; 
    audioPlayer.volume = 1.0f; 
    [audioPlayer prepareToPlay]; 

    if (audioPlayer == nil) 
    NSLog(@"%@", [error description]); 
    else 
    [audioPlayer play]; 
} 

任何幫助深表感謝。

+0

http://stackoverflow.com/questions/3275990/iphone-sdk-support-for-playing-mp3-files-over-the-network可能的幫助 – 2012-08-11 00:09:24

+0

很多後解決問題和花費時間,最後解決問題。它變得非常非常簡單。變量範圍。在我所有的三種方法中,我在方法中定義了玩家實例變量,只要方法執行完成,玩家變量引用計數就被設置爲ZERO(通過ARC)。所以我定義了一個類級別的變量,賦予了它的實例變量並且一切正常。 – Shas 2012-08-13 10:53:27

回答

0

嘗試使用MPMoviePlayerController。首先,您需要導入MediaPlayer框架。那麼它的,因爲這很容易:

MPMoviePlayerController *myAudioPlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:urlTextField.text]]; 
[myAudioPlayer play];