AVAudioPlayer播放/暂停/停止三个不同按钮上的本地音频文件

时间:2016-02-22 10:28:24

标签: objective-c avaudioplayer

我想播放/暂停/停止本地音频文件。所有功能的按钮都不同。查看附带的屏幕截图以供参考。

enter image description here

以下是我的点击事件

-(IBAction)click_Play:(id)sender {
        NSString *path;
        NSURL *url;

        //where you are about to add sound
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

        path =[[NSBundle mainBundle] pathForResource:@"MySong" ofType:@"mp3"];
        url = [NSURL fileURLWithPath:path];

        player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
        [player setVolume:1.0];
        [player prepareToPlay];
        [player play];

}

-(IBAction)click_Pause:(id)sender {
    [player pause];
}

-(IBAction)click_Stop:(id)sender {
    [player stop];
}

在这里,我在暂停功能方面面临问题。当我再次点击播放按钮暂停音频后。它从开始播放开始,而不是在我暂停播放的时候播放。有解决方案吗 提前谢谢!

2 个答案:

答案 0 :(得分:2)

将您的代码更改为:

-(IBAction)click_Play:(id)sender {
    if (!player)
    {
        NSString *path;
        NSURL *url;

        //where you are about to add sound
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

        path =[[NSBundle mainBundle] pathForResource:@"MySong" ofType:@"mp3"];
        url = [NSURL fileURLWithPath:path];

        player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
        [player setVolume:1.0];
        [player prepareToPlay];
        [player play];
    }
    else {
        [player play];
    }
}

答案 1 :(得分:1)

请勿在播放按钮操作中反复创建AVAudioSessionAVAudioPlayer的实例。所以,保持简单,在AVAudioSession

中创建AVAudioPlayerviewDidLoad的实例
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path;
    NSURL *url;

    //where you are about to add sound
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

    path =[[NSBundle mainBundle] pathForResource:@"MySong" ofType:@"mp3"];
    url = [NSURL fileURLWithPath:path];

    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    [player setVolume:1.0];
    [player prepareToPlay];
} 

-(IBAction)click_Play:(id)sender {
    [player play];
}

-(IBAction)click_Pause:(id)sender {
    [player pause];
}

-(IBAction)click_Stop:(id)sender {
    [player stop];
}

修改 当您改变轨道的内容时,请调用此方法。我永远不会建议一次又一次地创建对象实例

-(void)changeTrackWithPath:(NSString *)path{
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:path]];
    [player replaceCurrentItemWithPlayerItem:playerItem];
    [player play];
}