我对 AVFoundation 音乐播放器有一些问题。
1)它不会立即启动,我猜模拟器上的缓冲很慢?
2) 50% 的时候只有声音启动,其他 50% 不启动,非常不可靠
这是我的课
Music_Player.h
@interface Music_Player : NSObject <AVAudioPlayerDelegate>
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
@property (nonatomic, retain) NSString *trackPlaying;
@property (nonatomic) BOOL isPlaying;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) UISlider *slider;
-(void)initTrack: (NSString *) track;
-(void)startPlayer;
-(void)pausePlayer;
-(void)stopPlayer;
-(void)sliderUp;
-(void)sliderDown;
@end
音乐播放器.m
#import "Music Player.h"
@implementation Music_Player
@synthesize audioPlayer;
@synthesize trackPlaying;
@synthesize timer;
@synthesize isPlaying;
@synthesize slider;
-(void)initTrack:(NSString *)track
{
/* Init slider */
self.isPlaying = FALSE;
self.trackPlaying = track;
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:self.trackPlaying ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
[self.audioPlayer prepareToPlay];
/* Set slider max value */
self.slider.minimumValue = 0;
self.slider.maximumValue = self.audioPlayer.duration - 5;
}
-(void)startPlayer
{
if (self.isPlaying == TRUE)
{
NSLog(@"Pause clicked");
[self.audioPlayer pause];
self.isPlaying = FALSE;
} else {
NSLog(@"Play clicked");
[self.audioPlayer play];
self.isPlaying = TRUE;
if (![self.timer isValid]) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
}
}
}
- (void)updateTime {
if (self.isPlaying == TRUE) {
NSTimeInterval currentTime = self.audioPlayer.currentTime;
NSLog(@"%f", currentTime);
// update UI with currentTime;
slider.value = round(currentTime);
}
}
-(void)pausePlayer
{
if (self.isPlaying == TRUE)
{
[self.audioPlayer pause];
self.isPlaying = FALSE;
}
}
-(void)stopPlayer
{
if (self.isPlaying == TRUE)
{
NSLog(@"Stop clicked");
[self.audioPlayer stop];
self.audioPlayer.currentTime = 0;
self.slider.value = round(self.audioPlayer.currentTime);
self.isPlaying = FALSE;
}
}
-(void)sliderUp
{
if (self.isPlaying == FALSE)
{
self.audioPlayer.currentTime = round(slider.value);
[self.audioPlayer play];
self.isPlaying = TRUE;
}
}
-(void)sliderDown
{
if (self.isPlaying == TRUE)
{
self.isPlaying = FALSE;
[self.audioPlayer stop];
}
}
/* AUDIO PLAYER DELEGATES */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"Did finish with, %c", flag);
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
NSLog(@"Error %@",error);
}
@end
我刚刚设置了滑块属性并使用我的 viewController 中的轨道对其进行了初始化
/* Init Music */
self.music_player = [[Music_Player alloc] init];
self.music_player.slider = self.slider;
[self.music_player initTrack:@"track1"];
然后我只是将 Btn 点击和滑块值更改传递给 music_player 类,可能是什么问题?我明天将在 iPhone 上测试它,所以它可能只是一个模拟器问题吗?