我试图从AVPlayer上的网址播放.mp3。
url = [NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/jcq74691pet09d9/Chumbawamba%20-%20Tubthumping%20HD.mp3?dl=0"];
AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:url];
AVPlayer *player = [[AVPlayer alloc]initWithPlayerItem:item];
[player play];
我已导入AVFoundation.h
和AVFoundation.m
,并且网址链接也可用作直接/热门链接。
无法让它工作,我不知道为什么。
答案 0 :(得分:1)
// *** create AVAsset using URL ***
AVAsset *asset = [AVAsset assetWithURL:[NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/jcq74691pet09d9/Chumbawamba%20-%20Tubthumping%20HD.mp3?dl=0"]];
// *** Create AVPlayerItem using AVAsset ***
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:asset];
// *** Initialise AVPlayer ***
avPlayer = [AVPlayer playerWithPlayerItem:playerItem];
// *** Add AVPlayer to ViewController ***
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayerLayer.frame = CGRectMake(0, 0, 320, 480);
[avPlayerLayer setBackgroundColor:[UIColor grayColor].CGColor];
[self.view.layer addSublayer:avPlayerLayer];
// *** Start Playback ***
[avPlayer play];
// *** Register for playback end notification ***
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[avPlayer currentItem]];
// *** Register observer for events of AVPlayer status ***
[avPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
添加以下Observer方法以观察AVPlayer的播放状态
// *** Observe status event and perform actions ***
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == avPlayer && [keyPath isEqualToString:@"status"]) {
if (avPlayer.status == AVPlayerStatusFailed) {
NSLog(@"AVPlayer Failed");
} else if (avPlayer.status == AVPlayerStatusReadyToPlay) {
NSLog(@"AVPlayerStatusReadyToPlay");
[avPlayer play];
} else if (avPlayer.status == AVPlayerItemStatusUnknown) {
NSLog(@"AVPlayer Unknown");
}
}
}
答案 1 :(得分:0)
试试这样:
NSURL *myurl = [NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/jcq74691pet09d9/Chumbawamba%20-%20Tubthumping%20HD.mp3?dl=0"];
NSData *data = [NSData dataWithContentsOfURL:myurl];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:NULL];
audioPlayer.delegate = self;
[audioPlayer play];
您也可以编写Delegate方法:
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
[audioPlayer stop];
NSLog(@"Finished Playing");
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
NSLog(@"Something wrong");
}