[英]unable to play music from document directory through AVPlayer in iOS?
我正在使用MediaPickerController選擇音樂文件。在我從選擇器中選擇音樂文件后,我將文件保存到文檔目錄。
以下是選擇和保存到文檔目錄的代碼
//code to click on music button
- (IBAction)addMusic:(id)sender
{
MPMediaPickerController *soundPicker=[[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
soundPicker.delegate=self;
soundPicker.allowsPickingMultipleItems=NO;
[self presentViewController:soundPicker animated:YES completion:nil];
}
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
NSLog(@"music files delegate called");
MPMediaItem *item = [[mediaItemCollection items] objectAtIndex:0];
[self uploadMusicFile:item];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void) uploadMusicFile:(MPMediaItem *)song
{
NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
presetName:AVAssetExportPresetAppleM4A];
exporter.outputFileType = @"com.apple.m4a-audio";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * myDocumentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
[[NSDate date] timeIntervalSince1970];
NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
NSString *intervalSeconds = [NSString stringWithFormat:@"%0.0f",seconds];
NSString * fileName = [NSString stringWithFormat:@"%@.mp4",intervalSeconds];
NSString *exportFile = [myDocumentsDirectory stringByAppendingPathComponent:fileName];
NSURL *exportURL = [NSURL fileURLWithPath:exportFile];
exporter.outputURL = exportURL;
// do the export
// (completion handler block omitted)
[exporter exportAsynchronouslyWithCompletionHandler:
^{
int exportStatus = exporter.status;
switch (exportStatus)
{
case AVAssetExportSessionStatusFailed:
{
NSError *exportError = exporter.error;
NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
break;
}
case AVAssetExportSessionStatusCompleted:
{
NSLog (@"AVAssetExportSessionStatusCompleted");
//music data is NSdata
music_data = [NSData dataWithContentsOfFile: [myDocumentsDirectory
stringByAppendingPathComponent:fileName]];
// NSLog(@"Data %@",data);
// data = nil;
break;
}
case AVAssetExportSessionStatusUnknown:
{
NSLog (@"AVAssetExportSessionStatusUnknown"); break;
}
case AVAssetExportSessionStatusExporting:
{
NSLog (@"AVAssetExportSessionStatusExporting"); break;
}
case AVAssetExportSessionStatusCancelled:
{
NSLog (@"AVAssetExportSessionStatusCancelled"); break;
}
case AVAssetExportSessionStatusWaiting:
{
NSLog (@"AVAssetExportSessionStatusWaiting"); break;
}
default:
{
NSLog (@"didn't get export status"); break;
}
}
}];
}
用於播放文檔目錄中的音樂文件的代碼
- (void)musicPlay:(UIGestureRecognizer *)recognizer
{
if(!isMusicPlaying)
{
if([musicFile isEqualToString:@"none"])
{
NSLog(@"INSIDE IF");
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"No music exist" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
NSURL *fileURL;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
bc.music_upload=[bc.music_upload lastPathComponent];
NSLog(@"music uplaod is %@",bc.music_upload);
NSString* path = [documentsDirectory stringByAppendingPathComponent:bc.music_upload];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if(fileExists)
{
NSLog(@"file already exist");
fileURL = [NSURL fileURLWithPath:path];
NSLog(@"file url is %@",fileURL);
}
else
{
NSLog(@"file already not exist");
if(![musicFile containsString:@"http://"])
{
musicFile=[IMAGE_BASE_URL stringByAppendingString:musicFile];
}
fileURL = [NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:musicFile]];
}
NSLog(@"file url is %@",fileURL);
isMusicPlaying=true;
[self.img_music setImage:[UIImage imageNamed:@"play_stop.png"]];
playerItem = [AVPlayerItem playerItemWithURL:fileURL];
player = [AVPlayer playerWithPlayerItem:playerItem];
//player = [AVPlayer playerWithURL:path];
[player play];
}
}
else
{
isMusicPlaying=false;
[player pause];
[self.img_music setImage:[UIImage imageNamed:@"music-icon.png"]];
}
}
我能夠保存文件&當我檢查文件目錄中是否存在文件然后我能夠找到該文件。但我無法播放該文件。我不明白是什么問題。我的問題是音樂文件還是我的音樂播放器代碼? ' 編輯:我已經嘗試過這段代碼,但它正在讓應用程序掛起並且沒有響應。
NSURL *url = [NSURL URLWithString:@"http://sound18.mp3pk.com/pop_remix/ebodf11/ebodf11-15(www.songs.pk).mp3"];
NSData *data = [NSData dataWithContentsOfURL:url];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
[audioPlayer play];
編輯:
我認為問題在於將MPMediaItem轉換為NSdata 。因為當我將MPMediaItem轉換為NSData然后我能夠發送它服務器並且它在瀏覽器上播放。但是我嘗試使用AVPlayer然后我面臨這個問題?
來自Apple的文章
與資產和項目一樣,初始化播放器並不意味着它已准備好播放。 您應該觀察播放器的status屬性,該屬性在准備播放時會更改為AVPlayerStatusReadyToPlay。 您還可以觀察currentItem屬性以訪問為流創建的播放器項。
將觀察者添加到您的播放器
- (void)musicPlay:(UIGestureRecognizer *)recognizer {
// your player code
[player addObserver:self forKeyPath:@"status" options:0 context:nil];
}
// Observe for the player status
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == _player && [keyPath isEqualToString:@"status"]) {
if (_player.status == AVPlayerStatusFailed) {
NSLog(@"AVPlayer Failed");
} else if (_player.status == AVPlayerStatusReadyToPlay) {
NSLog(@"AVPlayerStatusReadyToPlay");
[_player play];
} else if (_player.status == AVPlayerItemStatusUnknown) {
NSLog(@"AVPlayer Unknown");
}
}
}
試試這個:
NSURL *url = [NSURL URLWithString:filePath]; // like file:///...
AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
if (asset) {
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player = [AVPlayer playerWithPlayerItem:item];
[player play];
}
您能否確保導入<AudioToolbox/AudioToolbox.h>
。
此外,使用ARC,您必須擁有對AVPlayer
對象的強引用。 請嘗試宣布一個強大的財產。
@property (strong, nonatomic) AVPlayer *player;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.