gpt4 book ai didi

iphone - iOS : How to avoid overlapping sound/music in PickerViewController

转载 作者:行者123 更新时间:2023-11-29 04:51:36 24 4
gpt4 key购买 nike

我有一个使用选择器 View 的具有多种声音的音乐播放器。我的问题是,当我单击下一首音乐时,上一首音乐将与我选择的音乐重叠。这意味着当我滚动选取器 View 以选择一个新对象时,它将播放新的音乐/声音,但上一个对象将重叠当前的选择。我想停止之前的音乐,这样就不会重叠。这是代码。

H 文件:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>

@interface PickerViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, AVAudioPlayerDelegate>{

UIPickerView *picker;
UILabel *musicTitle;
NSMutableArray *musicList;
AVAudioPlayer *audioPlayer;


}


@property (nonatomic, retain) IBOutlet UIPickerView *picker;
@property (nonatomic, retain) IBOutlet UILabel *musicTitle;
@property (nonatomic, retain) NSMutableArray *musicList;

-(IBAction)playSelectedMusic:(id)sender;


@end

M 文件:

     - (void)viewDidLoad
{
[super viewDidLoad];
musicList = [[NSMutableArray alloc] initWithObjects:@"m1",@"m2",@"m3",@"m6",@"m4", @"m5",nil];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component


{



if ([[musicList objectAtIndex:row] isEqual:@"m1"])
{

NSString *path = [[NSBundle mainBundle] pathForResource:@"m1" ofType:@"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

pickerView.delegate = self;
[theAudio play];
[theAudio setCurrentTime:0.0]; (our friend from this forum have suggested this but still doens't work)

NSString *resultString = [[NSString alloc] initWithFormat:
@"m1",
[musicList objectAtIndex:row]];
musicTitle.text = resultString;


}


if ([[musicList objectAtIndex:row] isEqual:@"m2"])
{

NSString *path = [[NSBundle mainBundle] pathForResource:@"m2" ofType:@"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

pickerView.delegate = self;
[theAudio play];
[theAudio setCurrentTime:0.0]; (our friend from this forum have suggested this but still doens't work)



NSString *resultString = [[NSString alloc] initWithFormat:
@"m2",
[musicList objectAtIndex:row]];
musicTitle.text = resultString;


}

代码修改:

 NSString *path = [[NSBundle mainBundle] pathForResource:@"you" ofType:@"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];

AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:file error:NULL];

[file release];

self.audioPlayer = theAudio;
[theAudio release];

[audioPlayer prepareToPlay];
[audioPlayer setDelegate:self];
[audioPlayer setNumberOfLoops:0];
[audioPlayer stop];

我的愚蠢错误:

@property (nonatomic, retain) AVAudioPlayer *audioPlayer;

最佳答案

只需停止当前正在播放的声音,然后再开始另一个声音,您的 AVAudioPlayer 是一个 ivar,因此您可以做到这一点。添加

[theAudio stop];

关于iphone - iOS : How to avoid overlapping sound/music in PickerViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8726508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com