IOS 播放本地音樂(播放記憶體卡中的MP3) 及 檔案的寫入
阿新 • • 發佈:2019-01-30
在IOS開發中, 每一個應用程式都擁有一個Documents的資料夾來存放自己的檔案。
在這裡為了測試, 我們首先得把mp3檔案匯入到專案中。
然後讀出資源裡的mp3檔案,寫入到documents中, 然後再從documents中讀取該mp3檔案來播放。
(在實際當中也許我們需要下載一首歌到本地檔案, 然後播放它)
//先獲取資原始檔路徑,然後轉換成NSData寫入到指定資料夾中
//使用AVAudioPlayer來播放指定音樂- (IBAction)ClickSave:(id)sender { NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"qyqx" ofType:@"mp3"]]; NSData *data = [[NSData alloc] initWithContentsOfURL:url]; NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/qyqx.mp3"]; [data writeToFile:filePath atomically:YES]; }
//AVAudioPlayer 必須在h檔案中定義, 否則播放不了音樂- (IBAction) ClickPly:(id)sender { NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/qyqx.mp3"]; _myPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil]; [_myPlay play]; }